'use client';

import { useAppStore } from '@/stores/app-store';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useState } from 'react';
import { BookOpen, GraduationCap, LogIn, Shield } from 'lucide-react';

export default function LoginPage() {
  const { login, isLoginTab, setLoginTab } = useAppStore();
  const [guruEmail, setGuruEmail] = useState('fatimah@gmail.com');
  const [guruPassword, setGuruPassword] = useState('guru123');
  const [ortuNama, setOrtuNama] = useState('');
  const [ortuPassword, setOrtuPassword] = useState('');
  const [kepsekEmail, setKepsekEmail] = useState('kepsek@gmail.com');
  const [kepsekPassword, setKepsekPassword] = useState('kepsek123');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const doLogin = async (url: string, body: Record<string, string>) => {
    setLoading(true);
    setError('');
    try {
      const res = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.error); return; }
      login(data);
    } catch { setError('Gagal terhubung ke server'); }
    finally { setLoading(false); }
  };

  const handleGuruLogin = (e: React.FormEvent) => {
    e.preventDefault();
    doLogin('/api/auth/login-guru', { email: guruEmail, password: guruPassword });
  };

  const handleOrtuLogin = (e: React.FormEvent) => {
    e.preventDefault();
    doLogin('/api/auth/login-ortu', { namaAnak: ortuNama, password: ortuPassword });
  };

  const handleKepsekLogin = (e: React.FormEvent) => {
    e.preventDefault();
    doLogin('/api/auth/login-kepsek', { email: kepsekEmail, password: kepsekPassword });
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-emerald-50 via-white to-teal-50 p-4">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-emerald-600 text-white mb-4 shadow-lg">
            <BookOpen className="w-8 h-8" />
          </div>
          <h1 className="text-2xl font-bold text-gray-900">Monitoring Ummi</h1>
          <p className="text-gray-500 mt-1">Pantau hafalan & bacaan Al-Quran santri</p>
        </div>

        <Card className="shadow-xl border-0">
          <CardHeader className="pb-4">
            <CardTitle className="flex items-center gap-2">
              <LogIn className="w-5 h-5 text-emerald-600" />
              Masuk
            </CardTitle>
            <CardDescription>Pilih cara masuk sesuai peran Anda</CardDescription>
          </CardHeader>
          <CardContent>
            <Tabs value={isLoginTab} onValueChange={(v) => setLoginTab(v as 'guru' | 'ortu' | 'kepsek')}>
              <TabsList className="grid w-full grid-cols-3 mb-4">
                <TabsTrigger value="kepsek" className="gap-1 text-xs sm:text-sm">
                  <Shield className="w-3.5 h-3.5" />
                  <span className="hidden sm:inline">Kepala</span> Sekolah
                </TabsTrigger>
                <TabsTrigger value="guru" className="gap-1 text-xs sm:text-sm">
                  <GraduationCap className="w-3.5 h-3.5" />
                  Guru
                </TabsTrigger>
                <TabsTrigger value="ortu" className="gap-1 text-xs sm:text-sm">
                  <BookOpen className="w-3.5 h-3.5" />
                  Ortu
                </TabsTrigger>
              </TabsList>

              {error && (
                <div className="bg-red-50 text-red-700 text-sm p-3 rounded-lg mb-4 border border-red-200">
                  {error}
                </div>
              )}

              {/* Kepala Sekolah Login */}
              <TabsContent value="kepsek">
                <form onSubmit={handleKepsekLogin} className="space-y-4">
                  <div className="space-y-2">
                    <Label>Email</Label>
                    <Input type="email" placeholder="email@sekolah.com" value={kepsekEmail} onChange={(e) => setKepsekEmail(e.target.value)} required />
                  </div>
                  <div className="space-y-2">
                    <Label>Password</Label>
                    <Input type="password" placeholder="Masukkan password" value={kepsekPassword} onChange={(e) => setKepsekPassword(e.target.value)} required />
                  </div>
                  <Button type="submit" className="w-full bg-emerald-700 hover:bg-emerald-800" disabled={loading}>
                    {loading ? 'Memproses...' : 'Masuk sebagai Kepala Sekolah'}
                  </Button>
                </form>
              </TabsContent>

              {/* Guru Login */}
              <TabsContent value="guru">
                <form onSubmit={handleGuruLogin} className="space-y-4">
                  <div className="space-y-2">
                    <Label>Email</Label>
                    <Input type="email" placeholder="email@guru.com" value={guruEmail} onChange={(e) => setGuruEmail(e.target.value)} required />
                  </div>
                  <div className="space-y-2">
                    <Label>Password</Label>
                    <Input type="password" placeholder="Masukkan password" value={guruPassword} onChange={(e) => setGuruPassword(e.target.value)} required />
                  </div>
                  <Button type="submit" className="w-full bg-emerald-600 hover:bg-emerald-700" disabled={loading}>
                    {loading ? 'Memproses...' : 'Masuk sebagai Guru'}
                  </Button>
                </form>
              </TabsContent>

              {/* Orang Tua Login */}
              <TabsContent value="ortu">
                <form onSubmit={handleOrtuLogin} className="space-y-4">
                  <div className="space-y-2">
                    <Label>Nama Anak</Label>
                    <Input type="text" placeholder="Masukkan nama lengkap anak" value={ortuNama} onChange={(e) => setOrtuNama(e.target.value)} required />
                  </div>
                  <div className="space-y-2">
                    <Label>Password</Label>
                    <Input type="password" placeholder="Masukkan password" value={ortuPassword} onChange={(e) => setOrtuPassword(e.target.value)} required />
                  </div>
                  <Button type="submit" className="w-full bg-emerald-600 hover:bg-emerald-700" disabled={loading}>
                    {loading ? 'Memproses...' : 'Masuk sebagai Orang Tua'}
                  </Button>
                </form>
              </TabsContent>
            </Tabs>

            <div className="mt-6 p-3 bg-gray-50 rounded-lg border">
              <p className="text-xs font-medium text-gray-500 mb-2">Demo Login:</p>
              <div className="text-xs text-gray-600 space-y-0.5">
                <p><span className="font-medium">Kepsek:</span> kepsek@gmail.com / kepsek123</p>
                <p><span className="font-medium">Guru:</span> fatimah@gmail.com / guru123</p>
                <p><span className="font-medium">Ortu:</span> Aisyah Putri / aisyah123</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <p className="text-center text-xs text-gray-400 mt-6">
          Metode Ummi — Monitoring Hafalan & Bacaan Al-Quran
        </p>
      </div>
    </div>
  );
}