
'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 { Order, OrderItem } from '@/lib/data';
import { AlertCircle, UploadCloud, CheckCircle2, Download } from 'lucide-react';
import { exportToCsv } from '@/lib/utils';
import { getMockTailoringItems } from '@/lib/data';

type ImportDialogProps = {
  isOpen: boolean;
  onOpenChange: (isOpen: boolean) => void;
  onImport: (items: Order[]) => void;
};

export function ImportOrdersDialog({ 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: 'ORD001', 
            memoId: 'M-101',
            customerId: 'CUST001',
            customer: 'John Doe',
            phone: '1234567890',
            type: 'pickup',
            status: 'New',
            date: '2023-10-01',
            deliveryDate: '2023-10-10',
            totalAmount: 1400,
            paidAmount: 700,
            totalArtisanWage: 450,
            items: 'Shirt (x1), Pant (x1)',
            artisan: 'Karim Rahman',
            cuttingMaster: 'Salma Akhter',
            artisanAssignedDate: '',
            artisanCompletedDate: '',
            cuttingCompletedDate: '',
        },
    ];
    exportToCsv(sampleData, 'orders_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', 'customer', 'phone', 'status', 'date', 'totalAmount', 'paidAmount', 'items'];
        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 tailoringItems = getMockTailoringItems();

        const typedData = results.data.map((row: any) => {
             const orderItems: OrderItem[] = (row.items || '').split(',').map((itemString: string) => {
                const match = itemString.trim().match(/(.+) \(x(\d+)\)/);
                if (!match) return null;

                const name = match[1].trim();
                const quantity = parseInt(match[2], 10);
                const tailoringItem = tailoringItems.find(ti => ti.name.toLowerCase() === name.toLowerCase());

                return {
                    id: `item-${Date.now()}-${Math.random()}`,
                    name,
                    quantity,
                    price: tailoringItem?.sewingPrice || 0,
                    artisanWage: tailoringItem?.artisanWage || 0,
                    measurements: '', // Measurements can't be reliably imported from a simple string
                };
            }).filter((item: OrderItem | null): item is OrderItem => item !== null);
            
            return {
                ...row,
                items: orderItems,
                totalAmount: parseFloat(row.totalAmount) || 0,
                paidAmount: parseFloat(row.paidAmount) || 0,
                totalArtisanWage: parseFloat(row.totalArtisanWage) || 0,
                type: ['pickup', 'delivery'].includes(row.type) ? row.type : 'pickup',
                status: ['New', 'In Progress', 'Ready for Delivery', 'Delivered', 'Completed', 'Cancelled'].includes(row.status) ? row.status : 'New',
            }
        });

        onImport(typedData as Order[]);
      },
      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 Orders from CSV</DialogTitle>
          <DialogDescription>
            Upload a CSV file with your order data. The `items` column should be formatted like: "Item Name (xQuantity), Another Item (xQuantity)".
          </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>
  );
}
