"use client"

import { useState } from "react"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { Upload, FileSpreadsheet, CheckCircle2, AlertCircle } from "lucide-react"

interface ImportStudentsDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onImport: (file: File) => void
}

export function ImportStudentsDialog({ open, onOpenChange, onImport }: ImportStudentsDialogProps) {
  const [file, setFile] = useState<File | null>(null)
  const [error, setError] = useState("")

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0]
    if (selectedFile) {
      if (
        selectedFile.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
        selectedFile.type === "application/vnd.ms-excel" ||
        selectedFile.type === "text/csv"
      ) {
        setFile(selectedFile)
        setError("")
      } else {
        setError("Veuillez sélectionner un fichier Excel ou CSV valide (.xlsx , .xls)")
        setFile(null)
      }
    }
  }

  const handleImport = async () => {
    if (!file) return

    try {
      onImport(file)
      setFile(null)
    } catch (err) {
      setError("Échec du traitement du fichier. Veuillez réessayer.")
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-lg bg-card">
        <DialogHeader>
          <DialogTitle>Importer des étudiants depuis Excel</DialogTitle>
          <DialogDescription>Charger un fichier Excel ou CSV contenant les données des étudiants</DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <Alert variant={"default"}>
            <FileSpreadsheet size={4}/>
            <AlertDescription className="text-sm">
              Le fichier doit contenir les colonnes : nom, classe, option, mtr, nni, téléphone, genre
            </AlertDescription>
          </Alert>

          {error && (
            <Alert variant={"destructive"}>
              <AlertCircle size={4}/>
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          <div className="flex flex-col items-center justify-center rounded-lg border-2 border-dashed border-border p-8">
            {file ? (
              <div className="flex flex-col items-center gap-2">
                <CheckCircle2 className="h-12 w-12 text-primary" />
                <p className="text-sm font-medium">{file.name}</p>
                <p className="text-xs text-muted-foreground">{(file.size / 1024).toFixed(2)} Ko</p>
                <Button variant="outline" size="sm" onClick={() => setFile(null)} className="mt-2 bg-transparent">
                  Choisir un autre fichier
                </Button>
              </div>
            ) : (
              <div className="flex flex-col items-center gap-2">
                <Upload className="h-12 w-12 text-muted-foreground" />
                <p className="text-sm font-medium">Choisir un fichier Excel </p>
                <p className="text-xs text-muted-foreground">Formats supportés : .xlsx, .xls</p>
                <label htmlFor="file-upload" className="mt-2">
                  <Button variant="outline" size="sm" asChild className="bg-transparent">
                    <span>Sélectionner un fichier</span>
                  </Button>
                  <input
                    id="file-upload"
                    type="file"
                    accept=".xlsx,.xls,.csv"
                    onChange={handleFileChange}
                    className="hidden"
                  />
                </label>
              </div>
            )}
          </div>

          <div className="flex justify-end gap-2">
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)} className="bg-transparent">
              Annuler
            </Button>
            <Button onClick={handleImport} disabled={!file}>
              Importer les étudiants
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
}
