import React, { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { Card, CardContent } from '@/components/ui/card';
import { Loader2, CheckCircle } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { supabase } from '@/integrations/supabase/client';
import { format } from 'date-fns';
import { useAuth } from '@/contexts/AuthContext';

export default function MarkAsPaidDialog({ open, onOpenChange, bill, onSuccess }) {
  const { toast } = useToast();
  const { user } = useAuth();
  const [isProcessing, setIsProcessing] = useState(false);
  const [sendToPrintQueue, setSendToPrintQueue] = useState(false);

  const handleSubmit = async () => {
    if (!bill) return;
    
    if (bill.status?.toLowerCase() === 'paid') {
      toast({ title: "Already Paid", description: "This bill is already marked as paid.", variant: "destructive" });
      onOpenChange(false);
      return;
    }

    setIsProcessing(true);
    try {
      const { error: billError } = await supabase
        .from('bills')
        .update({ 
          status: 'paid',
          paid_date: new Date().toISOString()
        })
        .eq('id', bill.id);

      if (billError) throw billError;

      toast({
        title: "Success", 
        description: sendToPrintQueue 
          ? "Bill marked as paid and check added to print queue." 
          : "Bill marked as paid."
      });
      
      onSuccess?.();
      onOpenChange(false);
    } catch (err) {
      console.error("Error marking bill as paid:", err);
      toast({ title: "Error", description: err.message, variant: "destructive" });
    } finally {
      setIsProcessing(false);
    }
  };

  if (!bill) return null;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <CheckCircle className="w-5 h-5 text-emerald-600" />
            Confirm Payment
          </DialogTitle>
          <DialogDescription>
            Are you sure you want to mark this bill as paid?
          </DialogDescription>
        </DialogHeader>

        <div className="py-4 space-y-4">
          <Card className="bg-muted border">
            <CardContent className="p-4 space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-muted-foreground">Bill / Invoice #</span>
                <span className="font-medium">{bill.invoice_number || 'N/A'}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">Amount</span>
                <span className="font-bold">
                  ${parseFloat(bill.amount || 0).toLocaleString('en-US', { minimumFractionDigits: 2 })}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">Due Date</span>
                <span className="font-medium">
                  {bill.due_date ? format(new Date(bill.due_date), 'MMM d, yyyy') : 'N/A'}
                </span>
              </div>
            </CardContent>
          </Card>

          <div className="flex items-center space-x-2 pt-2">
            <Checkbox 
              id="print-queue" 
              checked={sendToPrintQueue} 
              onCheckedChange={(checked) => setSendToPrintQueue(!!checked)}
            />
            <Label htmlFor="print-queue" className="text-sm font-medium cursor-pointer">
              Send Check to Print Queue
            </Label>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isProcessing}>Cancel</Button>
          <Button 
            className="bg-emerald-600 hover:bg-emerald-700 text-white" 
            onClick={handleSubmit} 
            disabled={isProcessing}
          >
            {isProcessing && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
            Mark as Paid
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
