import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Loader2, CheckCircle, AlertTriangle, FileText } from 'lucide-react';
import { validateBillData } from '@/lib/validateBillData';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';

export default function BillPDFReviewDialog({ open, onOpenChange, initialData, onConfirm, isProcessing }) {
  const [data, setData] = useState(initialData || {});
  const [errors, setErrors] = useState({});

  useEffect(() => {
    if (initialData) {
        setData({
            ...initialData,
            line_items: initialData.line_items || []
        });
        setErrors({});
    }
  }, [initialData]);

  const handleChange = (field, value) => {
    setData(prev => ({ ...prev, [field]: value }));
    if (errors[field]) {
        setErrors(prev => {
            const newErrs = { ...prev };
            delete newErrs[field];
            return newErrs;
        });
    }
  };

  const handleConfirm = () => {
      const validation = validateBillData(data);
      if (!validation.isValid) {
          setErrors(validation.errors);
          return;
      }
      onConfirm(data);
  };

  if (!initialData) return null;

  return (
    <Dialog open={open} onOpenChange={(val) => !isProcessing && onOpenChange(val)}>
      <DialogContent className="sm:max-w-[700px] h-[90vh] sm:h-auto flex flex-col">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <FileText className="h-5 w-5 text-primary" /> Review Extracted Data
          </DialogTitle>
          <DialogDescription>
            Please verify the details extracted from the invoice below.
          </DialogDescription>
        </DialogHeader>

        <ScrollArea className="flex-1 pr-4 -mr-4">
            <div className="space-y-6 py-2 p-1">
                {Object.keys(errors).length > 0 && (
                    <Alert variant="destructive">
                        <AlertTriangle className="h-4 w-4" />
                        <AlertTitle>Validation Errors</AlertTitle>
                        <AlertDescription>
                            Please correct the highlighted fields before proceeding.
                        </AlertDescription>
                    </Alert>
                )}

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                        <Label htmlFor="vendor_name">Vendor Name <span className="text-destructive">*</span></Label>
                        <Input 
                            id="vendor_name"
                            value={data.vendor_name || ''} 
                            onChange={(e) => handleChange('vendor_name', e.target.value)}
                            className={errors.vendor_name ? "border-destructive" : ""}
                        />
                        {errors.vendor_name && <p className="text-xs text-destructive">{errors.vendor_name}</p>}
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="invoice_number">Invoice Number</Label>
                        <Input 
                            id="invoice_number"
                            value={data.invoice_number || ''} 
                            onChange={(e) => handleChange('invoice_number', e.target.value)}
                        />
                    </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div className="space-y-2">
                        <Label htmlFor="amount">Total Amount <span className="text-destructive">*</span></Label>
                        <div className="relative">
                            <span className="absolute left-3 top-2.5 text-muted-foreground">$</span>
                            <Input 
                                id="amount"
                                type="number"
                                step="0.01"
                                className={`pl-7 ${errors.amount ? "border-destructive" : ""}`}
                                value={data.amount || ''} 
                                onChange={(e) => handleChange('amount', e.target.value)}
                            />
                        </div>
                        {errors.amount && <p className="text-xs text-destructive">{errors.amount}</p>}
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="bill_date">Invoice Date <span className="text-destructive">*</span></Label>
                        <Input 
                            id="bill_date"
                            type="date"
                            value={data.bill_date || ''} 
                            onChange={(e) => handleChange('bill_date', e.target.value)}
                            className={errors.bill_date ? "border-destructive" : ""}
                        />
                        {errors.bill_date && <p className="text-xs text-destructive">{errors.bill_date}</p>}
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="due_date">Due Date</Label>
                        <Input 
                            id="due_date"
                            type="date"
                            value={data.due_date || ''} 
                            onChange={(e) => handleChange('due_date', e.target.value)}
                        />
                    </div>
                </div>

                <div className="space-y-2">
                    <Label htmlFor="description">Description/Notes</Label>
                    <Textarea 
                        id="description"
                        value={data.description || ''} 
                        onChange={(e) => handleChange('description', e.target.value)}
                        rows={2}
                    />
                </div>
            </div>
        </ScrollArea>

        <DialogFooter className="mt-4 pt-4 border-t">
            <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isProcessing}>
                Cancel
            </Button>
            <Button onClick={handleConfirm} disabled={isProcessing} className="gap-2">
                {isProcessing ? (
                    <>
                        <Loader2 className="h-4 w-4 animate-spin" /> Processing...
                    </>
                ) : (
                    <>
                        <CheckCircle className="h-4 w-4" /> Confirm & Create Bill
                    </>
                )}
            </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
