"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Download, Loader2, FileSpreadsheet } from "lucide-react";
import { toast } from "sonner";
import { useJurusan } from "@/hooks/use-jurusan";

interface ExportSiswaProps {
  onExportStart?: () => void;
  onExportComplete?: () => void;
}

export function ExportSiswa({ onExportStart, onExportComplete }: ExportSiswaProps) {
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isExporting, setIsExporting] = useState(false);
  const [tingkat, setTingkat] = useState<string>("__all__");
  const [kelas, setKelas] = useState<string>("__all__");
  const [jurusanId, setJurusanId] = useState<string>("__all__");

  const { data: jurusanList } = useJurusan();

  // Available tingkat options
  const tingkatOptions = [
    { value: "__all__", label: "Semua Tingkat" },
    { value: "10", label: "Tingkat 10" },
    { value: "11", label: "Tingkat 11" },
    { value: "12", label: "Tingkat 12" },
  ];

  // Available kelas options
  const kelasOptions = [
    { value: "__all__", label: "Semua Kelas" },
    { value: "A", label: "Kelas A" },
    { value: "B", label: "Kelas B" },
    { value: "C", label: "Kelas C" },
    { value: "D", label: "Kelas D" },
    { value: "E", label: "Kelas E" },
  ];

  const handleExport = async () => {
    setIsExporting(true);

    if (onExportStart) {
      onExportStart();
    }

    try {
      // Build query parameters
      const params = new URLSearchParams();
      if (tingkat !== "__all__") {
        params.append("tingkat", tingkat);
      }
      if (kelas !== "__all__") {
        params.append("kelas", kelas);
      }
      if (jurusanId !== "__all__") {
        params.append("jurusanId", jurusanId);
      }

      const headers: Record<string, string> = {};

      // Add authorization header if token exists in localStorage
      const localToken = localStorage.getItem("token");
      if (localToken) {
        headers.Authorization = `Bearer ${localToken}`;
      }

      const response = await fetch(`/api/siswa/export?${params.toString()}`, {
        method: "GET",
        credentials: "include",
        headers,
      });

      if (response.ok) {
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;

        // Get filename from response headers or generate default
        const contentDisposition = response.headers.get("content-disposition");
        let filename = "data-siswa.xlsx";
        if (contentDisposition) {
          const filenameMatch = contentDisposition.match(/filename=([^;]+)/);
          if (filenameMatch) {
            filename = filenameMatch[1];
          }
        }

        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);

        toast.success("Data siswa berhasil diexport");
        setIsDialogOpen(false);

        if (onExportComplete) {
          onExportComplete();
        }
      } else {
        const errorData = await response.json();
        toast.error(errorData.message || "Gagal mengeksport data siswa");
      }
    } catch (error) {
      console.error("Error exporting siswa:", error);
      toast.error("Terjadi kesalahan saat mengeksport data siswa");
    } finally {
      setIsExporting(false);
    }
  };

  const handleClose = () => {
    setIsDialogOpen(false);
    setTingkat("__all__");
    setKelas("__all__");
    setJurusanId("__all__");
  };

  // Generate filter description for user feedback
  const getFilterDescription = () => {
    const filters = [];
    if (tingkat !== "__all__") {
      filters.push(`Tingkat ${tingkat}`);
    }
    if (kelas !== "__all__") {
      filters.push(`Kelas ${kelas}`);
    }
    if (jurusanId !== "__all__") {
      const jurusan = jurusanList?.find((j) => j.id === jurusanId);
      if (jurusan) {
        filters.push(`Jurusan ${jurusan.namaJurusan}`);
      }
    }

    if (filters.length === 0) {
      return "Semua data siswa";
    }

    return filters.join(", ");
  };

  return (
    <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
      <DialogTrigger asChild>
        <Button variant="outline">
          <Download className="mr-2 h-4 w-4" />
          Export Excel
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Export Data Siswa</DialogTitle>
          <DialogDescription>
            Export data siswa ke file Excel. Anda dapat memfilter data berdasarkan tingkat, kelas, dan jurusan.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6">
          {/* Filter Options */}
          <div className="space-y-4">
            <h3 className="text-sm font-medium">Filter Data (Opsional)</h3>

            {/* Tingkat Filter */}
            <div className="space-y-2">
              <Label htmlFor="tingkat">Tingkat</Label>
              <Select value={tingkat} onValueChange={setTingkat}>
                <SelectTrigger>
                  <SelectValue placeholder="Pilih tingkat" />
                </SelectTrigger>
                <SelectContent>
                  {tingkatOptions.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* Kelas Filter */}
            <div className="space-y-2">
              <Label htmlFor="kelas">Kelas</Label>
              <Select value={kelas} onValueChange={setKelas}>
                <SelectTrigger>
                  <SelectValue placeholder="Pilih kelas" />
                </SelectTrigger>
                <SelectContent>
                  {kelasOptions.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* Jurusan Filter */}
            <div className="space-y-2">
              <Label htmlFor="jurusan">Jurusan</Label>
              <Select value={jurusanId} onValueChange={setJurusanId}>
                <SelectTrigger>
                  <SelectValue placeholder="Pilih jurusan" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="__all__">Semua Jurusan</SelectItem>
                  {jurusanList?.map((jurusan) => (
                    <SelectItem key={jurusan.id} value={jurusan.id}>
                      {jurusan.namaJurusan} ({jurusan.kodeJurusan})
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* Preview */}
          <div className="bg-muted/50 rounded-md border p-3">
            <div className="flex items-center space-x-2">
              <FileSpreadsheet className="text-muted-foreground h-4 w-4" />
              <div className="text-sm">
                <p className="font-medium">Yang akan di-export:</p>
                <p className="text-muted-foreground">{getFilterDescription()}</p>
              </div>
            </div>
          </div>

          {/* Actions */}
          <div className="flex justify-end space-x-2">
            <Button variant="outline" onClick={handleClose} disabled={isExporting}>
              Batal
            </Button>
            <Button onClick={handleExport} disabled={isExporting}>
              {isExporting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Export Excel
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
