import React, { useState } from 'react';
import { Form, Input, Button, Typography, Alert, message } from 'antd';
import { LockOutlined, UserOutlined } from '@ant-design/icons';

const { Title } = Typography;


export default function LoginPage({ onLogin }) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const darkMode = typeof window !== 'undefined' && localStorage.getItem('darkMode') === 'true';

  const onFinish = async (values) => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(values),
      });
      const data = await res.json();
      if (data.success) {
        localStorage.setItem('jwt', data.token);
        message.success('Login erfolgreich!');
        setTimeout(() => {
          window.location.href = window.location.pathname + window.location.search || '/';
        }, 600);
        onLogin && onLogin(data);
      } else {
        setError(data.error?.message || 'Login fehlgeschlagen');
      }
    } catch (e) {
      setError('Serverfehler');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      style={{
        minHeight: '100dvh',
        width: '100vw',
        background: darkMode ? '#181818' : '#f5f5f5',
        transition: 'background 0.2s',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <div
        style={{
          width: 350,
          padding: 24,
          background: darkMode ? '#1f1f1f' : '#fff',
          borderRadius: 8,
          boxShadow: darkMode ? '0 2px 8px #222' : '0 2px 8px #eee',
          color: darkMode ? '#fff' : undefined
        }}
      >
        <Title level={3} style={{ textAlign: 'center', color: darkMode ? '#fff' : undefined }}>Anmeldung</Title>
        {error && <Alert type="error" message={error} showIcon style={{ marginBottom: 16 }} />}
        <Form name="login" onFinish={onFinish} layout="vertical">
          <Form.Item name="username" label={<span style={{ color: darkMode ? '#fff' : undefined }}>Benutzername (nur Admin)</span>} >
            <Input prefix={<UserOutlined />} placeholder="Benutzername" autoComplete="username" style={darkMode ? { background: '#222', color: '#fff' } : {}} />
          </Form.Item>
          <Form.Item name="password" label={<span style={{ color: darkMode ? '#fff' : undefined }}>Passwort</span>} rules={[{ required: true, message: 'Bitte Passwort eingeben!' }]}> 
            <Input.Password prefix={<LockOutlined />} placeholder="Passwort" autoComplete="current-password" style={darkMode ? { background: '#222', color: '#fff' } : {}} />
          </Form.Item>
          <Button type="primary" htmlType="submit" block loading={loading}>
            Einloggen
          </Button>
        </Form>
      </div>
    </div>
  );
}
