"use client";

import { useState, useRef } from "react";
import { Button } from "@/components/ui/button";
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, CheckCircle2, XCircle, AlertTriangle } from "lucide-react";
import { useRombel } from "@/hooks/use-rombel";
import { toast } from "sonner";

interface ImportRombelProps {
  onImportComplete?: () => void;
}

export function ImportRombel({ onImportComplete }: ImportRombelProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [file, setFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [result, setResult] = useState<{
    imported: number;
    total: number;
    errors: string[];
  } | null>(null);

  const fileInputRef = useRef<HTMLInputElement>(null);
  const { importRombel, downloadTemplate, isLoading } = useRombel();

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0];
    if (selectedFile) {
      // Validate file type
      const validTypes = [
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "application/vnd.ms-excel",
        "text/csv",
      ];
      if (!validTypes.includes(selectedFile.type)) {
        toast.error("Format file tidak valid. Gunakan file Excel (.xlsx, .xls) atau CSV.");
        return;
      }
      setFile(selectedFile);
      setResult(null);
    }
  };

  const handleUpload = async () => {
    if (!file) {
      toast.error("Pilih file terlebih dahulu");
      return;
    }

    setIsUploading(true);
    setUploadProgress(30);

    try {
      setUploadProgress(60);
      const importResult = await importRombel(file);

      console.log(importResult);
      setUploadProgress(100);

      if (importResult) {
        setResult(importResult);
        if (importResult.errors.length === 0) {
          toast.success(`Berhasil mengimpor ${importResult.imported} dari ${importResult.total} data rombel`);
        } else {
          toast.warning(`Impor selesai dengan ${importResult.errors.length} error`);
        }
        onImportComplete?.();
      } else {
        toast.error("Gagal mengimpor data");
      }
    } catch {
      toast.error("Terjadi kesalahan saat mengimpor data");
    } finally {
      setIsUploading(false);
    }
  };

  const handleDownloadTemplate = async () => {
    try {
      await downloadTemplate();
      toast.success("Template berhasil diunduh");
    } catch {
      toast.error("Gagal mengunduh template");
    }
  };

  const handleClose = () => {
    setIsOpen(false);
    setFile(null);
    setResult(null);
    setUploadProgress(0);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={(open) => (open ? setIsOpen(true) : handleClose())}>
      <DialogTrigger asChild>
        <Button variant="outline">
          <Upload className="mr-2 h-4 w-4" />
          Import
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Import Data Rombel</DialogTitle>
          <DialogDescription>Upload file Excel atau CSV untuk mengimpor data rombel secara massal</DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          {/* Download Template */}
          <div className="bg-muted/50 rounded-lg border p-4">
            <div className="flex items-start gap-3">
              <FileSpreadsheet className="text-primary mt-0.5 h-5 w-5" />
              <div className="flex-1">
                <h4 className="text-sm font-medium">Template Import</h4>
                <p className="text-muted-foreground mt-1 text-xs">
                  Download template untuk format data yang benar. Kolom yang diperlukan: Nama Rombel, Tingkat, Tahun
                  Pelajaran, Kode Jurusan (opsional)
                </p>
                <Button variant="link" size="sm" className="mt-2 h-auto p-0" onClick={handleDownloadTemplate}>
                  <Download className="mr-1 h-3 w-3" />
                  Download Template
                </Button>
              </div>
            </div>
          </div>

          {/* File Input */}
          <div className="space-y-2">
            <div
              className="hover:bg-muted/50 cursor-pointer rounded-lg border-2 border-dashed p-6 text-center transition-colors"
              onClick={() => fileInputRef.current?.click()}
            >
              {file ? (
                <div className="flex flex-col items-center gap-2">
                  <FileSpreadsheet className="text-primary h-8 w-8" />
                  <div>
                    <p className="text-sm font-medium">{file.name}</p>
                    <p className="text-muted-foreground text-xs">{(file.size / 1024).toFixed(2)} KB</p>
                  </div>
                </div>
              ) : (
                <div className="flex flex-col items-center gap-2">
                  <Upload className="text-muted-foreground h-8 w-8" />
                  <div>
                    <p className="text-sm font-medium">Klik untuk upload file</p>
                    <p className="text-muted-foreground text-xs">Format: .xlsx, .xls, .csv</p>
                  </div>
                </div>
              )}
            </div>
            <input
              ref={fileInputRef}
              type="file"
              accept=".xlsx,.xls,.csv"
              className="hidden"
              onChange={handleFileChange}
            />
          </div>

          {/* Upload Progress */}
          {isUploading && (
            <div className="space-y-2">
              <div className="flex items-center justify-between text-sm">
                <span>Mengimpor data...</span>
                <span>{uploadProgress}%</span>
              </div>
              <Progress value={uploadProgress} />
            </div>
          )}

          {/* Result */}
          {result && (
            <div className="space-y-3">
              <Alert variant={result.errors.length === 0 ? "default" : "destructive"}>
                <div className="flex items-center gap-2">
                  {result.errors.length === 0 ? (
                    <CheckCircle2 className="h-4 w-4 text-green-500" />
                  ) : (
                    <AlertTriangle className="h-4 w-4" />
                  )}
                  <AlertDescription>
                    Berhasil: {result.imported} dari {result.total} data
                  </AlertDescription>
                </div>
              </Alert>

              {result.errors.length > 0 && (
                <div className="max-h-32 space-y-1 overflow-y-auto rounded border p-2">
                  <p className="text-xs font-medium text-red-500">Detail Error:</p>
                  {result.errors.slice(0, 10).map((err, idx) => (
                    <div key={idx} className="flex items-start gap-1 text-xs text-red-500">
                      <XCircle className="mt-0.5 h-3 w-3 shrink-0" />
                      <span>{err}</span>
                    </div>
                  ))}
                  {result.errors.length > 10 && (
                    <p className="text-muted-foreground text-xs">...dan {result.errors.length - 10} error lainnya</p>
                  )}
                </div>
              )}
            </div>
          )}

          {/* Actions */}
          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={handleClose}>
              {result ? "Tutup" : "Batal"}
            </Button>
            {!result && (
              <Button onClick={handleUpload} disabled={!file || isUploading || isLoading}>
                {isUploading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Import Data
              </Button>
            )}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
