'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import toast from 'react-hot-toast';
import { Eye, EyeOff, Loader2 } from 'lucide-react';
import { authApi, setToken } from '@/lib/api';
import { LoginResponse } from '@/types';

// -----------------------------------------------------------------------
// Steps
// -----------------------------------------------------------------------
type Step = 'credentials' | 'first_login_setup' | 'setup_2fa' | 'otp';

// -----------------------------------------------------------------------
// Schemas
// -----------------------------------------------------------------------
const credSchema = z.object({
  username: z.string().min(1, 'Required'),
  password: z.string().min(1, 'Required'),
});

const firstLoginSchema = z.object({
  new_password: z
    .string()
    .min(8, 'Min 8 characters')
    .regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/, 'Must include upper, lower, digit, special'),
  new_password_confirmation: z.string(),
  display_name: z.string().min(1, 'Required').max(100),
  email: z.string().email('Valid email required'),
}).refine((d) => d.new_password === d.new_password_confirmation, {
  path: ['new_password_confirmation'],
  message: 'Passwords must match',
});

const otpSchema = z.object({
  otp: z.string().length(6, 'Must be 6 digits'),
  device_name: z.string().optional(),
});

// -----------------------------------------------------------------------
export default function LoginPage() {
  const router = useRouter();
  const [step, setStep] = useState<Step>('credentials');
  const [tempToken, setTempToken] = useState('');
  const [qrCode, setQrCode] = useState('');
  const [secret, setSecret] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  // Forms
  const credForm = useForm({ resolver: zodResolver(credSchema) });
  const firstLoginForm = useForm({ resolver: zodResolver(firstLoginSchema) });
  const otpForm = useForm({ resolver: zodResolver(otpSchema) });

  // ----------------------------------------------------------------
  // Step 1: Credentials
  // ----------------------------------------------------------------
  const handleLogin = credForm.handleSubmit(async (data) => {
    setIsLoading(true);
    try {
      const res = await authApi.login(data.username, data.password);
      const body: LoginResponse = res.data;

      if (body.step === 'first_login') {
        setTempToken(body.temp_token!);
        setStep('first_login_setup');
      } else if (body.step === 'setup_2fa') {
        setTempToken(body.temp_token!);
        setQrCode(body.qr_code!);
        setSecret(body.secret!);
        setStep('setup_2fa');
      } else if (body.step === 'otp') {
        setTempToken(body.temp_token!);
        setStep('otp');
      } else if (body.token) {
        setToken(body.token);
        router.push('/dashboard');
      }
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Login failed');
    } finally {
      setIsLoading(false);
    }
  });

  // ----------------------------------------------------------------
  // Step 2: First login setup
  // ----------------------------------------------------------------
  const handleFirstLoginSetup = firstLoginForm.handleSubmit(async (data) => {
    setIsLoading(true);
    try {
      const res = await authApi.firstLoginSetup(tempToken, {
        new_password: data.new_password,
        new_password_confirmation: data.new_password_confirmation,
        display_name: data.display_name,
        email: data.email,
      });
      const body: LoginResponse = res.data;
      setTempToken(body.temp_token!);
      setQrCode(body.qr_code!);
      setSecret(body.secret!);
      setStep('setup_2fa');
      toast.success('Profile updated! Now scan the QR code.');
    } catch (err: any) {
      const errors = err.response?.data?.errors;
      if (errors) {
        Object.entries(errors).forEach(([field, msgs]: any) => {
          firstLoginForm.setError(field as any, { message: msgs[0] });
        });
      } else {
        toast.error(err.response?.data?.message || 'Setup failed');
      }
    } finally {
      setIsLoading(false);
    }
  });

  // ----------------------------------------------------------------
  // Step 3: Confirm 2FA setup
  // ----------------------------------------------------------------
  const handleSetup2FA = otpForm.handleSubmit(async (data) => {
    setIsLoading(true);
    try {
      const res = await authApi.setup2fa(tempToken, data.otp, data.device_name);
      setToken(res.data.token);
      toast.success('2FA configured! Welcome.');
      router.push('/dashboard');
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Invalid OTP');
    } finally {
      setIsLoading(false);
    }
  });

  // ----------------------------------------------------------------
  // Step 4: OTP challenge
  // ----------------------------------------------------------------
  const handleOtp = otpForm.handleSubmit(async (data) => {
    setIsLoading(true);
    try {
      const res = await authApi.verifyOtp(tempToken, data.otp, data.device_name);
      setToken(res.data.token);
      toast.success('Signed in successfully');
      router.push('/dashboard');
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Invalid OTP');
    } finally {
      setIsLoading(false);
    }
  });

  // ----------------------------------------------------------------
  // Render
  // ----------------------------------------------------------------
  return (
    <div className="min-h-screen bg-ts-bg flex items-center justify-center p-4">
      <div className="w-full max-w-sm">
        {/* Logo / Brand */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-12 h-12 rounded-xl bg-ts-accent/10 border border-ts-accent/20 mb-4">
            <span className="text-ts-accent font-bold text-xl">T</span>
          </div>
          <h1 className="text-xl font-semibold text-ts-text">Tang Studio</h1>
          <p className="text-sm text-ts-muted mt-1">Administration Dashboard</p>
        </div>

        <div className="ts-card p-6">
          {/* ---- Credentials ---- */}
          {step === 'credentials' && (
            <>
              <h2 className="text-base font-semibold mb-5">Sign in</h2>
              <form onSubmit={handleLogin} className="space-y-4">
                <div>
                  <label className="ts-label">Username</label>
                  <input
                    {...credForm.register('username')}
                    className="ts-input"
                    placeholder="your-username"
                    autoComplete="username"
                  />
                  {credForm.formState.errors.username && (
                    <p className="text-xs text-red-400 mt-1">{credForm.formState.errors.username.message}</p>
                  )}
                </div>
                <div>
                  <label className="ts-label">Password</label>
                  <div className="relative">
                    <input
                      {...credForm.register('password')}
                      type={showPassword ? 'text' : 'password'}
                      className="ts-input pr-10"
                      placeholder="••••••••"
                      autoComplete="current-password"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-ts-muted hover:text-ts-text"
                    >
                      {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
                    </button>
                  </div>
                  {credForm.formState.errors.password && (
                    <p className="text-xs text-red-400 mt-1">{credForm.formState.errors.password.message}</p>
                  )}
                </div>
                <button type="submit" disabled={isLoading} className="ts-btn-primary w-full flex items-center justify-center gap-2">
                  {isLoading && <Loader2 size={16} className="animate-spin" />}
                  Continue
                </button>
              </form>
            </>
          )}

          {/* ---- First Login Setup ---- */}
          {step === 'first_login_setup' && (
            <>
              <h2 className="text-base font-semibold mb-1">Account Setup</h2>
              <p className="text-xs text-ts-muted mb-5">Set your password, display name, and email.</p>
              <form onSubmit={handleFirstLoginSetup} className="space-y-4">
                <div>
                  <label className="ts-label">Display Name</label>
                  <input {...firstLoginForm.register('display_name')} className="ts-input" placeholder="Your Name" />
                  {firstLoginForm.formState.errors.display_name && (
                    <p className="text-xs text-red-400 mt-1">{firstLoginForm.formState.errors.display_name.message as string}</p>
                  )}
                </div>
                <div>
                  <label className="ts-label">Email</label>
                  <input {...firstLoginForm.register('email')} type="email" className="ts-input" placeholder="you@example.com" />
                  {firstLoginForm.formState.errors.email && (
                    <p className="text-xs text-red-400 mt-1">{firstLoginForm.formState.errors.email.message as string}</p>
                  )}
                </div>
                <div>
                  <label className="ts-label">New Password</label>
                  <input {...firstLoginForm.register('new_password')} type="password" className="ts-input" />
                  <p className="text-xs text-ts-muted mt-1">Upper, lower, digit, special char required</p>
                  {firstLoginForm.formState.errors.new_password && (
                    <p className="text-xs text-red-400 mt-1">{firstLoginForm.formState.errors.new_password.message as string}</p>
                  )}
                </div>
                <div>
                  <label className="ts-label">Confirm Password</label>
                  <input {...firstLoginForm.register('new_password_confirmation')} type="password" className="ts-input" />
                  {firstLoginForm.formState.errors.new_password_confirmation && (
                    <p className="text-xs text-red-400 mt-1">{firstLoginForm.formState.errors.new_password_confirmation.message as string}</p>
                  )}
                </div>
                <button type="submit" disabled={isLoading} className="ts-btn-primary w-full flex items-center justify-center gap-2">
                  {isLoading && <Loader2 size={16} className="animate-spin" />}
                  Save & Continue
                </button>
              </form>
            </>
          )}

          {/* ---- Setup 2FA ---- */}
          {step === 'setup_2fa' && (
            <>
              <h2 className="text-base font-semibold mb-1">Set up Authenticator</h2>
              <p className="text-xs text-ts-muted mb-4">
                Scan this QR code with Google Authenticator or Authy. Up to 2 devices allowed.
              </p>
              {qrCode && (
                <div className="flex justify-center mb-4">
                  <img src={qrCode} alt="2FA QR Code" className="w-48 h-48 rounded" />
                </div>
              )}
              {secret && (
                <div className="bg-ts-bg rounded p-2 text-center mb-4">
                  <p className="text-xs text-ts-muted mb-1">Manual entry key</p>
                  <code className="text-xs font-mono text-ts-accent">{secret}</code>
                </div>
              )}
              <form onSubmit={handleSetup2FA} className="space-y-4">
                <div>
                  <label className="ts-label">Verification Code</label>
                  <input
                    {...otpForm.register('otp')}
                    className="ts-input text-center font-mono text-lg tracking-widest"
                    placeholder="000000"
                    maxLength={6}
                  />
                  {otpForm.formState.errors.otp && (
                    <p className="text-xs text-red-400 mt-1">{otpForm.formState.errors.otp.message}</p>
                  )}
                </div>
                <div>
                  <label className="ts-label">Device Name <span className="text-ts-muted">(optional)</span></label>
                  <input {...otpForm.register('device_name')} className="ts-input" placeholder="e.g. iPhone 15" />
                </div>
                <button type="submit" disabled={isLoading} className="ts-btn-primary w-full flex items-center justify-center gap-2">
                  {isLoading && <Loader2 size={16} className="animate-spin" />}
                  Verify & Activate
                </button>
              </form>
            </>
          )}

          {/* ---- OTP Challenge ---- */}
          {step === 'otp' && (
            <>
              <h2 className="text-base font-semibold mb-1">Two-Factor Authentication</h2>
              <p className="text-xs text-ts-muted mb-5">Enter the 6-digit code from your authenticator app.</p>
              <form onSubmit={handleOtp} className="space-y-4">
                <div>
                  <label className="ts-label">Authentication Code</label>
                  <input
                    {...otpForm.register('otp')}
                    className="ts-input text-center font-mono text-2xl tracking-widest"
                    placeholder="000000"
                    maxLength={6}
                    autoFocus
                  />
                  {otpForm.formState.errors.otp && (
                    <p className="text-xs text-red-400 mt-1">{otpForm.formState.errors.otp.message}</p>
                  )}
                </div>
                <button type="submit" disabled={isLoading} className="ts-btn-primary w-full flex items-center justify-center gap-2">
                  {isLoading && <Loader2 size={16} className="animate-spin" />}
                  Sign in
                </button>
                <button
                  type="button"
                  onClick={() => setStep('credentials')}
                  className="w-full text-sm text-ts-muted hover:text-ts-text transition-colors"
                >
                  ← Back to login
                </button>
              </form>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
