"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { createSuratIjin, getRiwayatIjin } from "./action";
import { toast } from "sonner";
import { Upload, FileText, CheckCircle, XCircle, Clock } from "lucide-react";
import { useAuth } from "@/contexts/auth-context";
import { useEffect } from "react";
import { Badge } from "@/components/ui/badge";

const schema = z.object({
  type: z.enum(["SAKIT", "IZIN"]),
  tanggal: z.string().min(1, "Tanggal wajib diisi"),
  keterangan: z.string().min(1, "Keterangan wajib diisi"),
  file: z.any().optional(), // File validation handles manually
});

export default function IjinPage() {
  const { user } = useAuth();
  const [loading, setLoading] = useState(false);
  const [riwayat, setRiwayat] = useState<any[]>([]);
  const [file, setFile] = useState<File | null>(null);

  const form = useForm({
    resolver: zodResolver(schema),
    defaultValues: {
      type: "SAKIT",
      tanggal: new Date().toISOString().split("T")[0],
      keterangan: "",
    },
  });

  useEffect(() => {
    if (user?.siswa?.id) {
      loadRiwayat(user.siswa.id);
    }
  }, [user]);

  async function loadRiwayat(siswaId: string) {
    const data = await getRiwayatIjin(siswaId);
    setRiwayat(data);
  }

  async function onSubmit(values: any) {
    if (!user?.siswa?.id) {
      toast.error("Data siswa tidak ditemukan");
      return;
    }
    setLoading(true);

    const formData = new FormData();
    formData.append("type", values.type);
    formData.append("tanggal", values.tanggal);
    formData.append("keterangan", values.keterangan);

    // File to Base64 for simple storage (in real app, upload to storage)
    if (file) {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = async () => {
        formData.append("fileUrl", reader.result as string);
        await submitData(formData, user?.siswa?.id);
      };
    } else {
      await submitData(formData, user?.siswa?.id);
    }
  }

  async function submitData(formData: FormData, siswaId: string) {
    const res = await createSuratIjin(formData, siswaId);
    if (res.success) {
      toast.success("Permohonan berhasil dikirim");
      form.reset();
      setFile(null);
      loadRiwayat(siswaId);
    } else {
      toast.error(res.error);
    }
    setLoading(false);
  }

  return (
    <div className="flex flex-col gap-6 p-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Perizinan Siswa</h1>
        <p className="text-muted-foreground">Ajukan surat izin atau keterangan sakit.</p>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {/* Form */}
        <Card>
          <CardHeader>
            <CardTitle>Form Pengajuan</CardTitle>
          </CardHeader>
          <CardContent>
            <Form {...form}>
              <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                <FormField
                  control={form.control}
                  name="type"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Jenis Izin</FormLabel>
                      <Select onValueChange={field.onChange} defaultValue={field.value}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="Pilih jenis" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="SAKIT">Sakit</SelectItem>
                          <SelectItem value="IZIN">Izin</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="tanggal"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Tanggal</FormLabel>
                      <FormControl>
                        <Input type="date" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="keterangan"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Keterangan</FormLabel>
                      <FormControl>
                        <Textarea placeholder="Jelaskan alasan..." {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormItem>
                  <FormLabel>Bukti (Surat/Foto)</FormLabel>
                  <div className="flex items-center gap-2">
                    <Input
                      type="file"
                      accept="image/*,application/pdf"
                      onChange={(e) => setFile(e.target.files?.[0] || null)}
                    />
                  </div>
                  <p className="text-muted-foreground text-xs">Format: JPG, PNG, PDF. Max 5MB.</p>
                </FormItem>

                <Button type="submit" className="w-full" disabled={loading}>
                  {loading ? "Mengirim..." : "Kirim Permohonan"}
                </Button>
              </form>
            </Form>
          </CardContent>
        </Card>

        {/* History */}
        <Card>
          <CardHeader>
            <CardTitle>Riwayat Pengajuan</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {riwayat.length === 0 ? (
                <p className="text-muted-foreground py-8 text-center">Belum ada riwayat.</p>
              ) : (
                riwayat.map((item) => (
                  <div key={item.id} className="flex items-start justify-between border-b pb-4 last:border-0 last:pb-0">
                    <div className="space-y-1">
                      <div className="flex items-center gap-2">
                        <Badge variant={item.type === "SAKIT" ? "destructive" : "default"}>{item.type}</Badge>
                        <span className="text-muted-foreground text-sm">
                          {new Date(item.tanggal).toLocaleDateString("id-ID")}
                        </span>
                      </div>
                      <p className="line-clamp-1 text-sm font-medium">{item.keterangan}</p>
                      {item.fileUrl && (
                        <a
                          href={item.fileUrl}
                          target="_blank"
                          className="text-primary flex items-center gap-1 text-xs hover:underline"
                        >
                          <FileText className="h-3 w-3" /> Lihat Lampiran
                        </a>
                      )}
                    </div>
                    <div>
                      {item.status === "PENDING" && (
                        <Badge variant="outline">
                          <Clock className="mr-1 h-3 w-3" /> Pending
                        </Badge>
                      )}
                      {item.status === "APPROVED" && (
                        <Badge className="bg-green-600">
                          <CheckCircle className="mr-1 h-3 w-3" /> Disetujui
                        </Badge>
                      )}
                      {item.status === "REJECTED" && (
                        <Badge variant="destructive">
                          <XCircle className="mr-1 h-3 w-3" /> Ditolak
                        </Badge>
                      )}
                    </div>
                  </div>
                ))
              )}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
