import { useState } from 'react';
import { Card, Form, Input, Button, Typography, Alert, Space } from 'antd';
import { LockOutlined, MailOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '@/stores/auth.store';

export default function LoginPage() {
  const navigate = useNavigate();
  const { login, error, isLoading } = useAuthStore();
  const [form] = Form.useForm();
  const [localError, setLocalError] = useState<string | null>(null);

  const handleSubmit = async (values: { email: string; password: string }) => {
    setLocalError(null);
    try {
      await login(values.email, values.password);
      navigate('/app');
    } catch {
      // Error is set in store
    }
  };

  const displayError = localError || error;

  return (
    <div
      style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        minHeight: '100vh',
        background: '#141414',
      }}
    >
      <Card style={{ width: 400, maxWidth: '90vw' }}>
        <Space direction="vertical" size="large" style={{ width: '100%' }}>
          <div style={{ textAlign: 'center' }}>
            <Typography.Title level={3} style={{ margin: 0 }}>
              Changemaker Control Panel
            </Typography.Title>
            <Typography.Text type="secondary">Sign in to manage instances</Typography.Text>
          </div>

          {displayError && (
            <Alert message={displayError} type="error" showIcon closable onClose={() => setLocalError(null)} />
          )}

          <Form form={form} onFinish={handleSubmit} layout="vertical" size="large">
            <Form.Item
              name="email"
              rules={[
                { required: true, message: 'Email is required' },
                { type: 'email', message: 'Enter a valid email' },
              ]}
            >
              <Input prefix={<MailOutlined />} placeholder="Email" autoFocus />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{ required: true, message: 'Password is required' }]}
            >
              <Input.Password prefix={<LockOutlined />} placeholder="Password" />
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit" loading={isLoading} block>
                Sign In
              </Button>
            </Form.Item>
          </Form>
        </Space>
      </Card>
    </div>
  );
}
