import { useState } from 'react';
import { Button } from '../ui/button';
import { Card, CardContent } from '../ui/card';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from '../ui/dialog';
import { signUp, sendVerificationEmail } from '../../lib/auth-client';
import { validateEmail } from '../../lib/validators';
import { useEffect } from 'react';

const logo = '/logo.png';

interface Props {
  onLogin: () => void;
  onVerify: () => void;
}

export function SignUpForm({ onLogin }: Props) {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [showVerifyDialog, setShowVerifyDialog] = useState(false);
  const [resendCooldown, setResendCooldown] = useState(0);
  const [resendLoading, setResendLoading] = useState(false);

  useEffect(() => {
    if (resendCooldown <= 0) return;
    const t = setTimeout(() => setResendCooldown(c => c - 1), 1000);
    return () => clearTimeout(t);
  }, [resendCooldown]);

  async function handleResend() {
    setResendLoading(true);
    await sendVerificationEmail({ email, callbackURL: window.location.origin });
    setResendLoading(false);
    setResendCooldown(60);
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError('');
    const trimmedName = name.trim();
    const trimmedEmail = email.trim();
    if (!validateEmail(trimmedEmail)) {
      setError('Please enter a valid email address.');
      return;
    }
    if (password.length < 8) {
      setError('Password must be at least 8 characters');
      return;
    }
    if (password !== confirm) {
      setError('Passwords do not match');
      return;
    }
    setLoading(true);
    const res = await signUp.email({
      name: trimmedName,
      email: trimmedEmail,
      password,
      callbackURL: window.location.origin,
    });
    setLoading(false);
    if (res.error) {
      setError(res.error.message || 'Failed to create account');
    } else {
      setShowVerifyDialog(true);
    }
  }

  return (
    <>
    <Dialog open={showVerifyDialog} onOpenChange={open => { if (!open) onLogin(); }}>
      <DialogContent className="max-w-sm">
        <DialogHeader>
          <DialogTitle>Check your inbox</DialogTitle>
          <DialogDescription asChild>
            <div className="space-y-2 text-sm text-muted-foreground">
              <p>
                We sent a verification link to{' '}
                <span className="font-medium text-foreground">{email}</span>.
              </p>
              <p>
                Click the link in the email to activate your account. If you don't see it, check your spam folder.
              </p>
            </div>
          </DialogDescription>
        </DialogHeader>
        <DialogFooter className="flex-col gap-2 sm:flex-col">
          <Button
            variant="outline"
            className="w-full"
            onClick={handleResend}
            disabled={resendLoading || resendCooldown > 0}
          >
            {resendLoading
              ? 'Sending…'
              : resendCooldown > 0
              ? `Resend in ${resendCooldown}s`
              : 'Resend verification email'}
          </Button>
          <Button className="w-full" onClick={onLogin}>
            Back to sign in
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
    <div className="flex h-screen items-center justify-center bg-secondary">
      <Card className="w-full max-w-sm">
        <CardContent className="p-8 space-y-6">
          <div className="flex justify-center">
            <a href="/"><img src={logo} alt="LabWise" className="h-12" /></a>
          </div>
          <p className="text-center text-muted-foreground text-sm">
            Create your LabWise account.
          </p>

          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-1">
              <Label htmlFor="name">
                Full name{' '}
                <span className="text-muted-foreground font-normal">(optional)</span>
              </Label>
              <Input
                id="name"
                type="text"
                value={name}
                onChange={e => setName(e.target.value)}
                autoComplete="name"
              />
            </div>
            <div className="space-y-1">
              <Label htmlFor="email">Email</Label>
              <Input
                id="email"
                type="email"
                value={email}
                onChange={e => setEmail(e.target.value)}
                required
                autoComplete="email"
              />
            </div>
            <div className="space-y-1">
              <Label htmlFor="password">Password</Label>
              <Input
                id="password"
                type="password"
                value={password}
                onChange={e => setPassword(e.target.value)}
                required
                autoComplete="new-password"
                placeholder="Min. 8 characters"
              />
            </div>
            <div className="space-y-1">
              <Label htmlFor="confirm">Confirm password</Label>
              <Input
                id="confirm"
                type="password"
                value={confirm}
                onChange={e => setConfirm(e.target.value)}
                required
                autoComplete="new-password"
              />
            </div>
            {error && <p className="text-sm text-red-600">{error}</p>}
            <Button type="submit" className="w-full" disabled={loading}>
              {loading ? 'Creating account…' : 'Create account'}
            </Button>
          </form>

          <p className="text-center text-sm text-muted-foreground">
            Already have an account?{' '}
            <button onClick={onLogin} className="text-primary hover:underline font-medium">
              Sign in
            </button>
          </p>
        </CardContent>
      </Card>
    </div>
    </>
  );
}
