import React, { useState, useEffect } from 'react';
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Loader2 } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';

export default function BillApprovalRequestDialog({ open, onOpenChange, billId, clientId, onSuccess }) {
  const [boardMembers, setBoardMembers] = useState([]);
  const [loadingMembers, setLoadingMembers] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  const [selectedMembers, setSelectedMembers] = useState([]);
  const [comment, setComment] = useState('');
  const { toast } = useToast();

  useEffect(() => {
    async function fetchBoardMembers() {
      if (!clientId || !open) return;
      setLoadingMembers(true);
      try {
        const { data, error } = await supabase
          .from('board_members')
          .select('*')
          .eq('association_id', clientId)
          .order('approval_authority', { ascending: false })
          .order('member_name', { ascending: true });

        if (error) throw error;
        setBoardMembers(data || []);
      } catch (err) {
        console.error("Failed to fetch board members", err);
      } finally {
        setLoadingMembers(false);
      }
    }
    fetchBoardMembers();
    setSelectedMembers([]);
    setComment('');
  }, [clientId, open]);

  const toggleMember = (id) => {
    setSelectedMembers(prev =>
      prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
    );
  };

  const handleSubmit = async () => {
    if (selectedMembers.length === 0) {
        toast({ title: 'Error', description: 'Please select at least one board member', variant: 'destructive' });
        return;
    }
    
    setIsSubmitting(true);
    try {
        await supabase.from('bills').update({ status: 'pending' }).eq('id', billId);

        const approvalRows = selectedMembers.map((memberId) => {
          const bm = boardMembers.find(b => b.id === memberId);
          return {
            association_id: clientId,
            bill_id: billId,
            vendor_name: bm?.member_name || 'Approver',
            status: 'pending',
            notes: comment || null,
          };
        });

        const { error } = await supabase.from('bill_approvals').insert(approvalRows);
        if (error) throw error;
        
        toast({ title: 'Success', description: `Approval request sent to ${selectedMembers.length} member(s).` });
        if (onSuccess) onSuccess();
        onOpenChange(false);
    } catch (err) {
        toast({ title: 'Error', description: err.message, variant: 'destructive' });
    } finally {
        setIsSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Request Approval</DialogTitle>
          <DialogDescription>
            Select board members with approval authority to review this bill.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <Label>Board Members</Label>
            <div className="border rounded-md p-3 max-h-[200px] overflow-y-auto bg-muted/30 space-y-2">
              {loadingMembers ? (
                <p className="text-sm text-muted-foreground italic">Loading...</p>
              ) : boardMembers.length === 0 ? (
                <p className="text-sm text-muted-foreground italic">No board members found for this association.</p>
              ) : (
                boardMembers.map(bm => (
                  <div key={bm.id} className="flex items-center space-x-2 bg-background p-2 rounded border">
                    <Checkbox
                      id={`req-bm-${bm.id}`}
                      checked={selectedMembers.includes(bm.id)}
                      onCheckedChange={() => toggleMember(bm.id)}
                    />
                    <Label htmlFor={`req-bm-${bm.id}`} className="cursor-pointer flex-1">
                      <span className="font-medium">{bm.member_name}</span>
                      {bm.approval_authority && (
                        <span className="ml-2 text-xs px-1.5 py-0.5 rounded bg-primary/10 text-primary">Approver</span>
                      )}
                      {bm.member_email && <span className="text-xs text-muted-foreground block">{bm.member_email}</span>}
                    </Label>
                  </div>
                ))
              )}
            </div>
            {selectedMembers.length > 0 && (
              <p className="text-xs text-muted-foreground">{selectedMembers.length} member(s) selected</p>
            )}
          </div>
          
          <div className="space-y-2">
            <Label>Comments (Optional)</Label>
            <Textarea 
              value={comment} 
              onChange={(e) => setComment(e.target.value)}
              placeholder="Add any notes for the approvers..."
            />
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>Cancel</Button>
          <Button onClick={handleSubmit} disabled={isSubmitting || selectedMembers.length === 0}>
            {isSubmitting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
            Send to {selectedMembers.length || ''} Approver{selectedMembers.length !== 1 ? 's' : ''}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
