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

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

export default function UploadFileMataKuliah({ onUploadSuccess }: UploadFileMataKuliahProps) {
  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/upload-mata-kuliah', {
        method: 'POST',
        body: formData,
      });
      
      const result = await response.json();
      
      if (!response.ok) {
        throw new Error(result.message || 'Upload failed');
      }
      
      showSuccess("Berhasil!", `${result.successCount} mata kuliah berhasil diimport`);
      onUploadSuccess();
      setIsDialogOpen(false);
      setSelectedFile(null);
      
      // Reset file input
      const fileInput = document.getElementById('file-upload') 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);
    }
  };

  // Download template
  const downloadTemplate = () => {
    // Create CSV template
    const csvContent = "kode_mk,nama_mk,sks,semester,jenis_mk,kode_prasyarat\nINF101,Pengantar Informatika,3,1,Wajib,\nINF102,Algoritma dan Pemrograman,4,2,Wajib,INF101\nINF301,Basis Data Lanjut,3,5,Pilihan Wajib,\nINF401,Topik Khusus,2,7,Pilihan,\n";
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'template_mata_kuliah.csv';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  };

  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 Mata Kuliah
            </DialogTitle>
          </DialogHeader>
          
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <label htmlFor="file-upload" className="text-sm font-medium">
                Pilih File Excel atau CSV
              </label>
              <Input
                id="file-upload"
                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>• Kolom yang diperlukan: kode_mk, nama_mk, sks, semester, jenis_mk</p>
                <p>• Kolom opsional: kode_prasyarat (kode mata kuliah prasyarat)</p>
                <p>• Baris pertama harus berisi header kolom</p>
                <p>• SKS dan semester harus berupa angka positif</p>
                <p>• jenis_mk harus salah satu: Wajib, Pilihan Wajib, Pilihan</p>
              </div>
              
              <Button
                variant="link"
                size="sm"
                onClick={downloadTemplate}
                className="p-0 h-auto mt-2 text-xs"
              >
                <Download className="mr-1 h-3 w-3" />
                Download Template CSV
              </Button>
            </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>
    </>
  );
}
