"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Progress } from "@/components/ui/progress";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Upload, Download, FileSpreadsheet, Loader2, AlertTriangle, CheckCircle } from "lucide-react";
import { toast } from "sonner";

interface ImportResult {
  imported: number;
  total: number;
  errors: number;
  errorDetails: string[];
}

interface ImportMapelProps {
  onImportComplete?: () => void;
}

export function ImportMapel({ onImportComplete }: ImportMapelProps) {
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [importResult, setImportResult] = useState<ImportResult | null>(null);

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      // Validate file type
      if (!file.name.endsWith(".xlsx") && !file.name.endsWith(".xls")) {
        toast.error("File harus berformat Excel (.xlsx atau .xls)");
        return;
      }

      // Validate file size (max 5MB)
      if (file.size > 5 * 1024 * 1024) {
        toast.error("Ukuran file tidak boleh lebih dari 5MB");
        return;
      }

      setSelectedFile(file);
      setImportResult(null);
    }
  };

  const handleUpload = async () => {
    if (!selectedFile) {
      toast.error("Pilih file terlebih dahulu");
      return;
    }

    setIsUploading(true);
    setUploadProgress(0);

    try {
      const formData = new FormData();
      formData.append("file", selectedFile);

      // Simulate progress
      const progressInterval = setInterval(() => {
        setUploadProgress((prev) => {
          if (prev >= 90) {
            clearInterval(progressInterval);
            return prev;
          }
          return prev + 10;
        });
      }, 200);

      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/mapel/import", {
        method: "POST",
        credentials: "include",
        headers,
        body: formData,
      });

      clearInterval(progressInterval);
      setUploadProgress(100);

      const result = await response.json();

      if (response.ok && result.success) {
        setImportResult(result.data);
        toast.success(result.message);

        // Call callback to refresh data
        if (onImportComplete) {
          onImportComplete();
        }
      } else {
        toast.error(result.message || "Gagal mengimpor data");
      }
    } catch (error) {
      console.error("Error importing file:", error);
      toast.error("Terjadi kesalahan saat mengimpor file");
    } finally {
      setIsUploading(false);
    }
  };

  const handleDownloadTemplate = async () => {
    try {
      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/mapel/import", {
        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;
        a.download = "template-mapel.xlsx";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);

        toast.success("Template berhasil didownload");
      } else {
        toast.error("Gagal mendownload template");
      }
    } catch (error) {
      console.error("Error downloading template:", error);
      toast.error("Terjadi kesalahan saat mendownload template");
    }
  };

  const handleClose = () => {
    setIsDialogOpen(false);
    setSelectedFile(null);
    setUploadProgress(0);
    setImportResult(null);
    setIsUploading(false);
  };

  return (
    <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
      <DialogTrigger asChild>
        <Button variant="outline">
          <Upload className="mr-2 h-4 w-4" />
          Import Excel
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Import Data Mata Pelajaran</DialogTitle>
          <DialogDescription>
            Upload file Excel untuk mengimpor data mata pelajaran dalam jumlah banyak.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6">
          {/* Download Template */}
          <div className="space-y-2">
            <Label>1. Download Template</Label>
            <Button variant="outline" onClick={handleDownloadTemplate} className="w-full">
              <Download className="mr-2 h-4 w-4" />
              Download Template Excel
            </Button>
            <p className="text-muted-foreground text-xs">
              Download template Excel dan isi data mata pelajaran sesuai format: Kode_Mapel dan Nama Mata Pelajaran.
            </p>
          </div>

          {/* File Upload */}
          <div className="space-y-2">
            <Label htmlFor="file">2. Pilih File Excel</Label>
            <Input id="file" type="file" accept=".xlsx,.xls" onChange={handleFileSelect} disabled={isUploading} />
            {selectedFile && (
              <div className="text-muted-foreground flex items-center space-x-2 text-sm">
                <FileSpreadsheet className="h-4 w-4" />
                <span>{selectedFile.name}</span>
                <span>({(selectedFile.size / 1024 / 1024).toFixed(2)} MB)</span>
              </div>
            )}
          </div>

          {/* Upload Progress */}
          {isUploading && (
            <div className="space-y-2">
              <div className="flex items-center space-x-2">
                <Loader2 className="h-4 w-4 animate-spin" />
                <span className="text-sm">Mengimpor data mata pelajaran...</span>
              </div>
              <Progress value={uploadProgress} className="w-full" />
            </div>
          )}

          {/* Import Result */}
          {importResult && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div className="flex items-center space-x-2">
                  <CheckCircle className="h-4 w-4 text-green-600" />
                  <span>Berhasil: {importResult.imported}</span>
                </div>
                <div className="flex items-center space-x-2">
                  <AlertTriangle className="h-4 w-4 text-amber-600" />
                  <span>Error: {importResult.errors}</span>
                </div>
              </div>

              {importResult.errors > 0 && (
                <Alert>
                  <AlertTriangle className="h-4 w-4" />
                  <AlertDescription>
                    <div className="space-y-1">
                      <p className="font-medium">Terdapat {importResult.errors} error:</p>
                      <ul className="list-inside list-disc space-y-1 text-sm">
                        {importResult.errorDetails.slice(0, 5).map((error, index) => (
                          <li key={index}>{error}</li>
                        ))}
                        {importResult.errorDetails.length > 5 && (
                          <li>... dan {importResult.errorDetails.length - 5} error lainnya</li>
                        )}
                      </ul>
                    </div>
                  </AlertDescription>
                </Alert>
              )}

              {importResult.imported > 0 && (
                <Alert>
                  <CheckCircle className="h-4 w-4 text-green-600" />
                  <AlertDescription>
                    <div className="space-y-1">
                      <p className="font-medium">Import berhasil!</p>
                      <p className="text-sm">{importResult.imported} mata pelajaran berhasil diimpor.</p>
                    </div>
                  </AlertDescription>
                </Alert>
              )}
            </div>
          )}

          {/* Actions */}
          <div className="flex justify-end space-x-2">
            <Button variant="outline" onClick={handleClose} disabled={isUploading}>
              {importResult ? "Selesai" : "Batal"}
            </Button>
            {!importResult && (
              <Button onClick={handleUpload} disabled={!selectedFile || isUploading}>
                {isUploading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Upload & Import
              </Button>
            )}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
