import { useState } from 'react';
import { Link } from 'react-router-dom';

import { INSTITUTIONAL_EMAIL_HINT, validateInstitutionalEmail } from './institutionalEmail';
import { forgotPassword } from './authOperations';
import { detailFromApiError } from '../api/client';
import { Button } from '../components/ui/button';
import { Input } from '../components/ui/input';
import { Label } from '../components/ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../components/ui/card';
import { Alert, AlertDescription } from '../components/ui/alert';
import { AlertCircle, Mail } from 'lucide-react';
import { Separator } from '../components/ui/separator';

/**
 * Forgot-password page — visual port of fe0/src/pages/ForgotPasswordPage.tsx.
 *
 * Markup/className tree preserved verbatim. The data call is rewired from fe0's
 * `authService.requestPasswordReset` (which returned `{ success, message, error }`)
 * to the shared `forgotPassword(email)` which resolves with the server message and
 * throws on error — failures surface via `detailFromApiError`.
 */
export function ForgotPasswordPage() {
  const [email, setEmail] = useState('');
  const [error, setError] = useState('');
  const [successMessage, setSuccessMessage] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setSuccessMessage('');
    const em = email.trim().toLowerCase();
    if (!validateInstitutionalEmail(em)) {
      setError('Vui lòng dùng email UMP hoặc UMC (đuôi @ump.edu.vn / @umc.edu.vn).');
      return;
    }
    setIsLoading(true);
    try {
      const message = await forgotPassword(em);
      setSuccessMessage(message || 'Nếu email tồn tại, hướng dẫn đặt lại mật khẩu đã được gửi.');
    } catch (err) {
      setError(detailFromApiError(err, 'Yêu cầu thất bại.'));
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-background p-4">
      <div className="w-full max-w-xl">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-foreground">Quên mật khẩu</h1>
          <p className="text-muted-foreground mt-2">Nhập email UMP hoặc UMC đã đăng ký</p>
        </div>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Mail className="h-5 w-5" />
              Khôi phục tài khoản
            </CardTitle>
            <CardDescription>
              <span className="text-xs text-muted-foreground">{INSTITUTIONAL_EMAIL_HINT}</span>
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="forgot-email">Email</Label>
                <Input
                  id="forgot-email"
                  type="email"
                  autoComplete="email"
                  placeholder="ten@ump.edu.vn"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                />
              </div>

              {error && (
                <Alert variant="destructive">
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription>{error}</AlertDescription>
                </Alert>
              )}

              {successMessage && (
                <Alert>
                  <AlertDescription>{successMessage}</AlertDescription>
                </Alert>
              )}

              <div className="flex justify-center">
                <Button type="submit" disabled={isLoading}>
                  {isLoading ? 'Đang xử lý...' : 'Gửi hướng dẫn'}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>

        <Separator className="my-6" />

        <div className="text-center space-y-2">
          <Link to="/login" className="text-sm text-muted-foreground hover:text-foreground block">
            ← Quay lại đăng nhập
          </Link>
          <Link to="/" className="text-sm text-muted-foreground hover:text-foreground block">
            Trang chủ
          </Link>
        </div>
      </div>
    </div>
  );
}
