"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { 
  Dialog, 
  DialogContent, 
  DialogHeader, 
  DialogTitle, 
  DialogTrigger,
  DialogFooter,
  DialogClose
} from "@/components/ui/dialog";
import { 
  FileUp, 
  Loader2,
  AlertCircle
} from "lucide-react";
import { useToast } from "@/components/ui/toast-provider";

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

export default function UploadFileBeasiswaMahasiswa({ onUploadSuccess }: UploadFileBeasiswaMahasiswaProps) {
  const { showSuccess, showError } = useToast();
  const [file, setFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0];
    setError(null);
    
    if (!selectedFile) {
      setFile(null);
      return;
    }
    
    // Check file type
    const fileType = selectedFile.type;
    const validTypes = [
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'text/csv',
      'application/csv',
      'text/plain'
    ];
    
    if (!validTypes.includes(fileType) && 
        !selectedFile.name.endsWith('.xlsx') && 
        !selectedFile.name.endsWith('.xls') &&
        !selectedFile.name.endsWith('.csv')) {
      setError("Format file tidak valid. Harap unggah file Excel (.xlsx, .xls) atau CSV (.csv)");
      setFile(null);
      return;
    }
    
    // Check file size (max 5MB)
    if (selectedFile.size > 5 * 1024 * 1024) {
      setError("Ukuran file terlalu besar. Maksimum 5MB");
      setFile(null);
      return;
    }
    
    setFile(selectedFile);
  };

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

    try {
      setIsUploading(true);
      setError(null);
      
      const formData = new FormData();
      formData.append('file', file);
      
      const response = await fetch('/api/keloladata/data-beasiswa-mahasiswa/upload', {
        method: 'POST',
        body: formData,
      });
      
      const result = await response.json();
      
      if (!response.ok) {
        throw new Error(result.message || 'Terjadi kesalahan saat mengunggah file');
      }
      
      setIsDialogOpen(false);
      setFile(null);
      onUploadSuccess();
      showSuccess("Berhasil!", "Data beasiswa berhasil diunggah");
    } catch (err) {
      console.error('Error uploading file:', err);
      setError((err as Error).message || 'Terjadi kesalahan saat mengunggah file');
      showError("Gagal!", (err as Error).message);
    } finally {
      setIsUploading(false);
    }
  };

  return (
    <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
      <DialogTrigger asChild>
        <Button variant="outline">
          <FileUp className="mr-2 h-4 w-4" />
          Upload Beasiswa
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Upload Data Beasiswa Mahasiswa</DialogTitle>
        </DialogHeader>
        <div className="space-y-4 py-4">
          <div className="text-sm text-muted-foreground">
            <p>Upload file Excel (.xlsx, .xls) atau CSV (.csv)</p>
          </div>
          
          <div className="grid w-full max-w-sm items-center gap-1.5">
            <label htmlFor="file-upload" className="text-sm font-medium">
              Pilih File
            </label>
            <input
              id="file-upload"
              type="file"
              className="file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-primary file:text-primary-foreground hover:file:bg-primary/90 text-sm text-muted-foreground"
              accept=".xlsx,.xls,.csv"
              onChange={handleFileChange}
            />
            {file && (
              <p className="text-xs text-muted-foreground mt-1">
                File terpilih: {file.name}
              </p>
            )}
          </div>
          
          {error && (
            <div className="bg-destructive/10 text-destructive text-sm p-2 rounded-md flex items-start">
              <AlertCircle className="h-4 w-4 mr-2 mt-0.5 flex-shrink-0" />
              <span>{error}</span>
            </div>
          )}
        </div>
        <DialogFooter>
          <DialogClose asChild>
            <Button type="button" variant="outline">
              Batal
            </Button>
          </DialogClose>
          <Button onClick={handleUpload} disabled={!file || isUploading}>
            {isUploading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Upload
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
} 