"use client";

import { useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { 
  Dialog, 
  DialogContent, 
  DialogHeader, 
  DialogTitle, 
  DialogFooter,
  DialogClose
} from "@/components/ui/dialog";
import { Upload, FileText, Loader2, X, CheckCircle, AlertCircle } from "lucide-react";
import { useToast } from "@/components/ui/toast-provider";

interface UploadExcelDosenProps {
  onUploadSuccess: () => void;
}

export default function UploadExcelDosen({ onUploadSuccess }: UploadExcelDosenProps) {
  const { showSuccess, showError } = useToast();
  const fileInputRef = useRef<HTMLInputElement>(null);

  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadResult, setUploadResult] = useState<any>(null);

  // Handle file selection
  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      // Validate file type
      const allowedTypes = [
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-excel',
        'text/csv'
      ];
      
      if (allowedTypes.includes(file.type)) {
        setSelectedFile(file);
      } else {
        showError("File tidak valid", "Silakan pilih file Excel (.xlsx, .xls) atau CSV (.csv)");
        e.target.value = '';
      }
    }
  };

  // Handle file upload
  const handleUpload = async () => {
    if (!selectedFile) {
      showError("Tidak ada file", "Silakan pilih file terlebih dahulu");
      return;
    }

    try {
      setIsUploading(true);
      
      const formData = new FormData();
      formData.append('file', selectedFile);

      const response = await fetch('/api/keloladata/data-dosen/upload', {
        method: 'POST',
        body: formData,
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.message || 'Upload failed');
      }

      setUploadResult(result);
      
      if (result.details.successCount > 0) {
        showSuccess("Upload berhasil!", result.message);
        onUploadSuccess(); // Refresh the main table
      } else {
        showError("Upload gagal", "Tidak ada data yang berhasil diupload");
      }

    } catch (error) {
      console.error('Upload error:', error);
      showError("Error", error instanceof Error ? error.message : "Terjadi kesalahan saat upload");
    } finally {
      setIsUploading(false);
    }
  };

  // Reset dialog
  const resetDialog = () => {
    setSelectedFile(null);
    setUploadResult(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  // Close dialog
  const handleDialogClose = () => {
    setIsDialogOpen(false);
    resetDialog();
  };

  return (
    <>
      <Button variant="outline" onClick={() => setIsDialogOpen(true)}>
        <Upload className="mr-2 h-4 w-4" />
        Upload Excel
      </Button>

      <Dialog open={isDialogOpen} onOpenChange={handleDialogClose}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>Upload Data Dosen</DialogTitle>
          </DialogHeader>
          
          <div className="space-y-4 py-4">
            {/* Instructions */}
            <div className="bg-blue-50 p-4 rounded-lg">
              <h4 className="font-medium text-blue-900 mb-2">Petunjuk Upload:</h4>
              <ul className="text-sm text-blue-800 space-y-1">
                <li>• File harus berformat Excel (.xlsx, .xls) atau CSV (.csv)</li>
                <li>• Kolom yang diperlukan: <strong>nama_dosen</strong>, <strong>nip</strong></li>
                <li>• NIP harus terdiri dari 18 karakter</li>
                <li>• Jika NIP sudah ada, data akan diupdate</li>
                <li>• Baris pertama harus berisi header kolom</li>
              </ul>
            </div>

            {/* File Input */}
            <div className="space-y-2">
              <label className="text-sm font-medium">Pilih File:</label>
              <div className="flex items-center gap-2">
                <Input
                  ref={fileInputRef}
                  type="file"
                  accept=".xlsx,.xls,.csv"
                  onChange={handleFileSelect}
                  className="flex-1"
                />
                {selectedFile && (
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={resetDialog}
                  >
                    <X className="h-4 w-4" />
                  </Button>
                )}
              </div>
              {selectedFile && (
                <div className="flex items-center gap-2 text-sm text-green-600">
                  <FileText className="h-4 w-4" />
                  <span>{selectedFile.name}</span>
                  <span className="text-muted-foreground">
                    ({(selectedFile.size / 1024).toFixed(1)} KB)
                  </span>
                </div>
              )}
            </div>

            {/* Upload Result */}
            {uploadResult && (
              <div className="space-y-3">
                <div className="bg-gray-50 p-4 rounded-lg">
                  <h4 className="font-medium mb-2">Hasil Upload:</h4>
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div className="flex items-center gap-2 text-green-600">
                      <CheckCircle className="h-4 w-4" />
                      <span>Berhasil: {uploadResult.details.successCount}</span>
                    </div>
                    <div className="flex items-center gap-2 text-red-600">
                      <AlertCircle className="h-4 w-4" />
                      <span>Gagal: {uploadResult.details.failedCount}</span>
                    </div>
                  </div>
                  <div className="text-sm text-muted-foreground mt-2">
                    Total baris: {uploadResult.details.totalRows}
                  </div>
                </div>

                {/* Show errors if any */}
                {uploadResult.details.errors && uploadResult.details.errors.length > 0 && (
                  <div className="bg-red-50 p-4 rounded-lg max-h-60 overflow-y-auto">
                    <h5 className="font-medium text-red-900 mb-2">Error Details:</h5>
                    <div className="space-y-1">
                      {uploadResult.details.errors.slice(0, 10).map((error: string, index: number) => (
                        <div key={index} className="text-sm text-red-800">
                          {error}
                        </div>
                      ))}
                      {uploadResult.details.errors.length > 10 && (
                        <div className="text-sm text-red-600 font-medium">
                          ... dan {uploadResult.details.errors.length - 10} error lainnya
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>

          <DialogFooter>
            <DialogClose asChild>
              <Button type="button" variant="outline">
                Tutup
              </Button>
            </DialogClose>
            <Button 
              onClick={handleUpload} 
              disabled={!selectedFile || isUploading}
            >
              {isUploading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {isUploading ? "Uploading..." : "Upload"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
