
'use client';

import React, { useState, useCallback } from 'react';
import { useDropzone } from 'react-dropzone';
import Papa from 'papaparse';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import type { Employee, EmployeeRole } from '@/lib/data';
import { AlertCircle, UploadCloud, CheckCircle2, Download } from 'lucide-react';
import { exportToCsv } from '@/lib/utils';
import { employeeRoles } from '@/lib/data';

type ImportDialogProps = {
  isOpen: boolean;
  onOpenChange: (isOpen: boolean) => void;
  onImport: (items: Employee[]) => void;
};

export function ImportEmployeesDialog({ isOpen, onOpenChange, onImport }: ImportDialogProps) {
  const [file, setFile] = useState<File | null>(null);
  const [error, setError] = useState<string | null>(null);

  const onDrop = useCallback((acceptedFiles: File[]) => {
    if (acceptedFiles.length > 0) {
      const uploadedFile = acceptedFiles[0];
      if (uploadedFile.type === 'text/csv') {
        setFile(uploadedFile);
        setError(null);
      } else {
        setError('Invalid file type. Please upload a CSV file.');
        setFile(null);
      }
    }
  }, []);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: { 'text/csv': ['.csv'] },
    multiple: false,
  });
  
  const handleDownloadSample = () => {
    const sampleData = [
        { 
            id: 'EMP001', 
            name: 'Karim Rahman', 
            phone: '01712345678', 
            role: 'Tailor',
            monthlySalary: 0
        },
        { 
            id: 'EMP002', 
            name: 'Salma Akhter', 
            phone: '01987654321', 
            role: 'Manager',
            monthlySalary: 25000
        },
    ];
    exportToCsv(sampleData, 'employees_sample.csv');
  };


  const handleImport = () => {
    if (!file) {
      setError('Please select a file to import.');
      return;
    }

    Papa.parse(file, {
      header: true,
      skipEmptyLines: true,
      complete: (results) => {
        if (results.errors.length > 0) {
          setError(`Error parsing CSV: ${results.errors[0].message}`);
          return;
        }

        const requiredHeaders = ['id', 'name', 'phone', 'role', 'monthlySalary'];
        const headers = results.meta.fields || [];
        const missingHeaders = requiredHeaders.filter(h => !headers.includes(h));

        if (missingHeaders.length > 0) {
            setError(`Missing required columns in CSV: ${missingHeaders.join(', ')}`);
            return;
        }
        
        const typedData = results.data.map((row: any) => ({
            ...row,
            role: employeeRoles.includes(row.role) ? row.role : 'Assistant',
            monthlySalary: parseFloat(row.monthlySalary) || 0
        }));

        onImport(typedData as Employee[]);
      },
      error: (err: any) => {
        setError(`An unexpected error occurred: ${err.message}`);
      },
    });
  };

  const handleClose = () => {
    setFile(null);
    setError(null);
    onOpenChange(false);
  }

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Import Employees from CSV</DialogTitle>
          <DialogDescription>
            Upload a CSV file with your employee data. The file must contain columns: `id`, `name`, `phone`, `role`, `monthlySalary`.
          </DialogDescription>
           <Button variant="link" onClick={handleDownloadSample} className="justify-start p-0 h-auto">
                <Download className="mr-2 h-4 w-4" />
                Download Sample CSV
            </Button>
        </DialogHeader>
        
        <div
          {...getRootProps()}
          className={`mt-4 flex justify-center items-center w-full h-48 border-2 border-dashed rounded-lg cursor-pointer
          ${isDragActive ? 'border-primary bg-primary/10' : 'border-border hover:border-primary/50'}`}
        >
          <input {...getInputProps()} />
          <div className="flex flex-col items-center justify-center gap-2 text-muted-foreground">
            {file ? (
                <>
                    <CheckCircle2 className="h-10 w-10 text-green-500" />
                    <p className="font-medium">{file.name}</p>
                    <p className="text-xs">File ready for import.</p>
                </>
            ) : (
                <>
                    <UploadCloud className="h-10 w-10" />
                    {isDragActive ? (
                        <p>Drop the file here...</p>
                    ) : (
                        <p>Drag & drop a CSV file here, or click to select</p>
                    )}
                </>
            )}
          </div>
        </div>

        {error && (
            <Alert variant="destructive" className="mt-4">
                <AlertCircle className="h-4 w-4" />
                <AlertTitle>Import Error</AlertTitle>
                <AlertDescription>{error}</AlertDescription>
            </Alert>
        )}

        <DialogFooter className="mt-4">
          <Button variant="outline" onClick={handleClose}>Cancel</Button>
          <Button onClick={handleImport} disabled={!file}>
            Import Data
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
