"use client";

import { useState } 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, FileSpreadsheet, Loader2 } from "lucide-react";
import { useToast } from "@/components/ui/toast-provider";

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

export default function UploadFileNilaiMahasiswa({ onUploadSuccess }: UploadFileNilaiMahasiswaProps) {
  const { showSuccess, showError } = useToast();
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);

  // Handle file selection
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      // Validate file type
      const validTypes = [
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'text/csv'
      ];
      
      if (!validTypes.includes(file.type)) {
        showError("Error!", "File harus berformat Excel (.xlsx, .xls) atau CSV (.csv)");
        return;
      }
      
      setSelectedFile(file);
    }
  };

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

    try {
      setIsUploading(true);
      
      const formData = new FormData();
      formData.append('file', selectedFile);
      
      const response = await fetch('/api/keloladata/data-nilai-mahasiswa/upload', {
        method: 'POST',
        body: formData,
      });
      
      const result = await response.json();
      
      if (!response.ok) {
        let errorMessage = result.message || 'Upload failed';
        if (result.errors && result.errors.length > 0) {
          errorMessage += '\n\nErrors:\n' + result.errors.slice(0, 5).join('\n');
        }
        throw new Error(errorMessage);
      }
      
      showSuccess("Berhasil!", `${result.successCount} nilai mahasiswa berhasil diimport`);
      onUploadSuccess();
      setIsDialogOpen(false);
      setSelectedFile(null);
      
      // Reset file input
      const fileInput = document.getElementById('file-upload-nilai') as HTMLInputElement;
      if (fileInput) {
        fileInput.value = '';
      }
    } catch (error) {
      console.error('Upload error:', error);
      showError("Gagal!", error instanceof Error ? error.message : "Terjadi kesalahan saat upload");
    } finally {
      setIsUploading(false);
    }
  };

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

      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <FileSpreadsheet className="h-5 w-5" />
              Import Data Nilai Mahasiswa
            </DialogTitle>
          </DialogHeader>
          
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <label htmlFor="file-upload-nilai" className="text-sm font-medium">
                Pilih File Excel atau CSV
              </label>
              <Input
                id="file-upload-nilai"
                type="file"
                accept=".xlsx,.xls,.csv"
                onChange={handleFileChange}
                className="cursor-pointer"
              />
              <p className="text-xs text-muted-foreground">
                Format yang didukung: .xlsx, .xls, .csv (Max: 10MB)
              </p>
            </div>
            
            {selectedFile && (
              <div className="p-3 bg-muted rounded-md">
                <p className="text-sm font-medium">File terpilih:</p>
                <p className="text-sm text-muted-foreground">{selectedFile.name}</p>
                <p className="text-xs text-muted-foreground">
                  Ukuran: {(selectedFile.size / 1024 / 1024).toFixed(2)} MB
                </p>
              </div>
            )}
            
            <div className="border-t pt-4">
              <h4 className="text-sm font-medium mb-2">Format File:</h4>
              <div className="text-xs text-muted-foreground space-y-1">
                <p>• <strong>Header kolom:</strong> NIM, Kode MK, Semester, Nilai Huruf, Nilai Angka</p>
                <p>• <strong>NIM:</strong> Harus sudah terdaftar di sistem (contoh: D1041231002)</p>
                <p>• <strong>Kode MK:</strong> Harus sesuai persis dengan database (contoh: INF-55201-101)</p>
                <p>• <strong>Semester:</strong> Angka 1-8</p>
                <p>• <strong>Nilai Huruf:</strong> A, B+, B, C+, C, D+, D, E</p>
                <p>• <strong>Nilai Angka:</strong> 0-4 (bisa menggunakan koma: 3,5 atau titik: 3.5)</p>
              </div>
            </div>
          </div>
          
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">
                Batal
              </Button>
            </DialogClose>
            <Button 
              onClick={handleUpload} 
              disabled={!selectedFile || isUploading}
            >
              {isUploading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {isUploading ? "Mengupload..." : "Upload"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
