'use client';

import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { useRouter } from 'next/navigation';

import { Eye, EyeOff, Loader2, Copy, Check, LogIn } from 'lucide-react';
import { toast } from 'sonner';
import AppLogo from '@/components/ui/AppLogo';

interface LoginFormValues {
  email: string;
  password: string;
  remember: boolean;
}

interface DemoCredential {
  role: string;
  email: string;
  password: string;
  badge: string;
  badgeClass: string;
}

const demoCredentials: DemoCredential[] = [
  { role: 'Admin', email: 'admin@cloudcorepos.co.ke', password: 'Admin@2026!', badge: 'Full Access', badgeClass: 'badge-danger' },
  { role: 'Manager', email: 'manager@cloudcorepos.co.ke', password: 'Manager@2026!', badge: 'Branch Level', badgeClass: 'badge-warning' },
  { role: 'Cashier', email: 'cashier@cloudcorepos.co.ke', password: 'Cashier@2026!', badge: 'POS Only', badgeClass: 'badge-info' },
];

export default function LoginForm() {
  const router = useRouter();
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [copiedField, setCopiedField] = useState<string | null>(null);

  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
    setError,
  } = useForm<LoginFormValues>({
    defaultValues: { email: '', password: '', remember: false },
  });

  const handleCopy = (text: string, key: string) => {
    navigator.clipboard.writeText(text).then(() => {
      setCopiedField(key);
      setTimeout(() => setCopiedField(null), 1500);
    });
  };

  const autofill = (cred: DemoCredential) => {
    setValue('email', cred.email, { shouldValidate: true });
    setValue('password', cred.password, { shouldValidate: true });
  };

  // Backend integration point: POST /api/auth/login
  const onSubmit = async (data: LoginFormValues) => {
    setIsLoading(true);
    await new Promise((r) => setTimeout(r, 1600));

    const valid = demoCredentials.find(
      (c) => c.email === data.email && c.password === data.password
    );

    if (!valid) {
      setIsLoading(false);
      setError('email', { message: 'Invalid credentials — use the demo accounts below to sign in' });
      return;
    }

    toast.success(`Welcome back! Signed in as ${valid.role}`);
    setTimeout(() => router.push('/dashboard'), 400);
  };

  return (
    <div className="flex-1 flex flex-col items-center justify-center min-h-screen bg-background px-6 py-10">
      {/* Mobile logo */}
      <div className="flex lg:hidden items-center gap-2 mb-8">
        <AppLogo size={36} />
        <span className="text-xl font-800 text-foreground">CloudCorePOS</span>
      </div>

      <div className="w-full max-w-md">
        {/* Header */}
        <div className="mb-8">
          <h2 className="text-2xl font-700 text-foreground mb-1">Sign in to your account</h2>
          <p className="text-sm text-muted-foreground">
            Enter your credentials to access the POS dashboard
          </p>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-5" noValidate>
          {/* Email */}
          <div>
            <label htmlFor="email" className="block text-sm font-600 text-foreground mb-1.5">
              Email Address
            </label>
            <input
              id="email"
              type="email"
              autoComplete="email"
              placeholder="you@cloudcorepos.co.ke"
              className={`w-full h-10 px-3 text-sm bg-card border rounded-md outline-none transition-all duration-150 placeholder:text-muted-foreground text-foreground
                ${errors.email ? 'border-danger ring-1 ring-danger/30' : 'border-input focus:border-primary focus:ring-1 focus:ring-primary/20'}`}
              {...register('email', {
                required: 'Email is required',
                pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: 'Enter a valid email address' },
              })}
            />
            {errors.email && (
              <p className="mt-1.5 text-xs text-danger flex items-center gap-1">
                {errors.email.message}
              </p>
            )}
          </div>

          {/* Password */}
          <div>
            <div className="flex items-center justify-between mb-1.5">
              <label htmlFor="password" className="block text-sm font-600 text-foreground">
                Password
              </label>
              <button type="button" className="text-xs text-primary hover:underline font-500">
                Forgot password?
              </button>
            </div>
            <div className="relative">
              <input
                id="password"
                type={showPassword ? 'text' : 'password'}
                autoComplete="current-password"
                placeholder="Enter your password"
                className={`w-full h-10 px-3 pr-10 text-sm bg-card border rounded-md outline-none transition-all duration-150 placeholder:text-muted-foreground text-foreground
                  ${errors.password ? 'border-danger ring-1 ring-danger/30' : 'border-input focus:border-primary focus:ring-1 focus:ring-primary/20'}`}
                {...register('password', {
                  required: 'Password is required',
                  minLength: { value: 6, message: 'Password must be at least 6 characters' },
                })}
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
              >
                {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
              </button>
            </div>
            {errors.password && (
              <p className="mt-1.5 text-xs text-danger">{errors.password.message}</p>
            )}
          </div>

          {/* Remember me */}
          <div className="flex items-center gap-2">
            <input
              id="remember"
              type="checkbox"
              className="w-4 h-4 rounded border-input accent-primary"
              {...register('remember')}
            />
            <label htmlFor="remember" className="text-sm text-muted-foreground cursor-pointer">
              Remember me for 30 days
            </label>
          </div>

          {/* Submit */}
          <button
            type="submit"
            disabled={isLoading}
            className={`w-full h-10 rounded-md text-sm font-600 flex items-center justify-center gap-2 transition-all duration-150
              ${isLoading
                ? 'bg-primary/60 text-white cursor-not-allowed' :'btn-primary text-white'
              }`}
          >
            {isLoading ? (
              <>
                <Loader2 size={16} className="animate-spin" />
                <span>Signing in…</span>
              </>
            ) : (
              <>
                <LogIn size={16} />
                <span>Sign In</span>
              </>
            )}
          </button>
        </form>

        {/* Demo credentials */}
        <div className="mt-8">
          <div className="flex items-center gap-2 mb-3">
            <div className="flex-1 h-px bg-border" />
            <span className="text-xs text-muted-foreground px-2 font-500">Demo Accounts</span>
            <div className="flex-1 h-px bg-border" />
          </div>

          <div className="card-elevated rounded-lg overflow-hidden">
            <div className="grid grid-cols-12 bg-muted/50 px-3 py-2 border-b border-border">
              <span className="col-span-2 text-xs font-600 text-muted-foreground">Role</span>
              <span className="col-span-5 text-xs font-600 text-muted-foreground">Email</span>
              <span className="col-span-3 text-xs font-600 text-muted-foreground">Access</span>
              <span className="col-span-2 text-xs font-600 text-muted-foreground text-center">Use</span>
            </div>
            {demoCredentials.map((cred) => (
              <div
                key={`cred-${cred.role.toLowerCase()}`}
                className="grid grid-cols-12 items-center px-3 py-2.5 border-b last:border-0 border-border hover:bg-muted/30 transition-colors"
              >
                <span className="col-span-2 text-xs font-700 text-foreground">{cred.role}</span>
                <div className="col-span-5 flex items-center gap-1">
                  <span className="text-xs text-muted-foreground font-mono truncate">{cred.email.split('@')[0]}</span>
                  <button
                    type="button"
                    onClick={() => handleCopy(cred.email, `email-${cred.role}`)}
                    className="flex-shrink-0 p-0.5 text-muted-foreground hover:text-primary transition-colors"
                    title="Copy email"
                  >
                    {copiedField === `email-${cred.role}` ? <Check size={11} className="text-success" /> : <Copy size={11} />}
                  </button>
                </div>
                <span className={`col-span-3 text-xs px-1.5 py-0.5 rounded-full font-600 inline-flex items-center w-fit ${cred.badgeClass}`}>
                  {cred.badge}
                </span>
                <div className="col-span-2 flex justify-center">
                  <button
                    type="button"
                    onClick={() => autofill(cred)}
                    className="text-xs font-600 text-primary hover:bg-primary/10 px-2 py-1 rounded transition-colors"
                  >
                    Fill
                  </button>
                </div>
              </div>
            ))}
          </div>
          <p className="text-xs text-muted-foreground mt-2 text-center">
            Click Fill to autofill credentials, then Sign In
          </p>
        </div>

        {/* Footer */}
        <p className="text-xs text-muted-foreground text-center mt-8">
          By signing in you agree to our{' '}
          <span className="text-primary cursor-pointer hover:underline">Terms of Service</span>
          {' '}and{' '}
          <span className="text-primary cursor-pointer hover:underline">Privacy Policy</span>
        </p>
      </div>
    </div>
  );
}