"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { ScrollArea } from "@/components/ui/scroll-area";
import { FileSpreadsheet, Download, Upload, AlertCircle, CheckCircle2 } from "lucide-react";
import { useJurusan } from "@/hooks/use-jurusan";
import { toast } from "sonner";

interface ImportJurusanProps {
  onSuccess?: () => void;
}

export function ImportJurusan({ onSuccess }: ImportJurusanProps) {
  const [file, setFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [importResults, setImportResults] = useState<any>(null);

  const { importJurusan, downloadTemplate } = useJurusan();

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

      // Validate file size (max 5MB)
      if (selectedFile.size > 5 * 1024 * 1024) {
        toast.error("Ukuran file maksimal 5MB");
        return;
      }

      setFile(selectedFile);
      setImportResults(null);
    }
  };

  const handleDownloadTemplate = () => {
    try {
      downloadTemplate();
      toast.success("Template berhasil diunduh");
    } catch (error) {
      toast.error("Gagal mengunduh template");
    }
  };

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

    setIsUploading(true);
    setUploadProgress(0);

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

    try {
      const result = await importJurusan(file);
      setUploadProgress(100);
      setImportResults(result.data);
      toast.success(result.message);

      if (onSuccess && result.data.success > 0) {
        onSuccess();
      }
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Gagal mengimpor data");
      setImportResults(null);
    } finally {
      clearInterval(progressInterval);
      setIsUploading(false);
      setUploadProgress(0);
    }
  };

  const handleReset = () => {
    setFile(null);
    setImportResults(null);
    setUploadProgress(0);
    // Reset file input
    const fileInput = document.getElementById("file-upload") as HTMLInputElement;
    if (fileInput) {
      fileInput.value = "";
    }
  };

  return (
    <div className="space-y-4">
      {/* Download Template */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <div className="rounded-lg bg-blue-100 p-2">
                <FileSpreadsheet className="h-5 w-5 text-blue-600" />
              </div>
              <div>
                <h3 className="font-medium">Template Excel</h3>
                <p className="text-muted-foreground text-sm">Unduh template untuk format yang benar</p>
              </div>
            </div>
            <Button variant="outline" onClick={handleDownloadTemplate}>
              <Download className="mr-2 h-4 w-4" />
              Unduh Template
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* File Upload */}
      <Card>
        <CardContent className="pt-6">
          <div className="space-y-4">
            <div>
              <label htmlFor="file-upload" className="mb-2 block text-sm font-medium">
                Pilih File Excel
              </label>
              <input
                id="file-upload"
                type="file"
                accept=".xlsx,.xls"
                onChange={handleFileChange}
                className="block w-full text-sm text-gray-500 file:mr-4 file:rounded-md file:border-0 file:bg-blue-50 file:px-4 file:py-2 file:text-sm file:font-medium file:text-blue-700 hover:file:bg-blue-100"
              />
              <p className="text-muted-foreground mt-1 text-xs">Format: .xlsx atau .xls, Maksimal 5MB</p>
            </div>

            {file && (
              <Alert>
                <FileSpreadsheet className="h-4 w-4" />
                <AlertDescription>
                  File terpilih: <strong>{file.name}</strong> ({(file.size / 1024 / 1024).toFixed(2)} MB)
                </AlertDescription>
              </Alert>
            )}

            {isUploading && (
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span>Mengimpor data...</span>
                  <span>{uploadProgress}%</span>
                </div>
                <Progress value={uploadProgress} className="w-full" />
              </div>
            )}

            <div className="flex space-x-2">
              <Button onClick={handleUpload} disabled={!file || isUploading} className="flex-1">
                <Upload className="mr-2 h-4 w-4" />
                {isUploading ? "Mengimpor..." : "Import Data"}
              </Button>
              {file && (
                <Button variant="outline" onClick={handleReset} disabled={isUploading}>
                  Reset
                </Button>
              )}
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Import Results */}
      {importResults && (
        <Card>
          <CardContent className="pt-6">
            <div className="space-y-4">
              <div className="flex items-center space-x-2">
                <CheckCircle2 className="h-5 w-5 text-green-600" />
                <h3 className="font-medium">Hasil Import</h3>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="rounded-lg bg-green-50 p-3">
                  <div className="text-sm font-medium text-green-600">Berhasil</div>
                  <div className="text-2xl font-bold text-green-700">{importResults.success}</div>
                </div>
                <div className="rounded-lg bg-red-50 p-3">
                  <div className="text-sm font-medium text-red-600">Gagal</div>
                  <div className="text-2xl font-bold text-red-700">{importResults.failed}</div>
                </div>
              </div>

              {importResults.errors && importResults.errors.length > 0 && (
                <div className="space-y-2">
                  <div className="flex items-center space-x-2 text-red-600">
                    <AlertCircle className="h-4 w-4" />
                    <span className="text-sm font-medium">Error Details:</span>
                  </div>
                  <ScrollArea className="h-32 w-full rounded-md border p-2">
                    <div className="space-y-1">
                      {importResults.errors.map((error: any, index: number) => (
                        <div key={index} className="text-xs">
                          <span className="font-medium">Baris {error.row}:</span> {error.error}
                        </div>
                      ))}
                    </div>
                  </ScrollArea>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
