import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { useAuth } from '@/contexts/AuthContext';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import ExpenseBundleSelector from '@/components/ExpenseBundleSelector';

export default function ExpenseBundleDialog({ open, onOpenChange, onSuccess, bundle, preselectedIds }) {
  const { user } = useAuth();
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [associations, setAssociations] = useState([]);
  
  const [formData, setFormData] = useState({
    association_id: '',
    name: '',
    description: '',
  });

  const [selectedExpenseIds, setSelectedExpenseIds] = useState(new Set());

  useEffect(() => {
    if (open) {
      fetchAssociations();
      if (bundle) {
        setFormData({
          association_id: bundle.client_id || '',
          name: bundle.name,
          description: bundle.description || '',
        });
        fetchBundleExpenses(bundle.id);
      } else if (preselectedIds && preselectedIds.size > 0) {
        setFormData({ association_id: '', name: '', description: '' });
        setSelectedExpenseIds(new Set(preselectedIds));
      } else {
        setFormData({ association_id: '', name: '', description: '' });
        setSelectedExpenseIds(new Set());
      }
    }
  }, [open, bundle]);

  const fetchAssociations = async () => {
    const { data } = await supabase.from('associations').select('id, name').eq('status', 'active').order('name');
    setAssociations(data || []);
  };

  const fetchBundleExpenses = async (bundleId) => {
    const { data, error } = await supabase
      .from('bundle_expenses')
      .select('expense_id, fee_schedule_id')
      .eq('bundle_id', bundleId);
    if (data && !error) {
      setSelectedExpenseIds(
        new Set(
          data
            .map((item) => item.expense_id || (item.fee_schedule_id ? `fee:${item.fee_schedule_id}` : null))
            .filter(Boolean)
        )
      );
    }
  };

  const handleAssociationChange = (associationId) => {
    if (associationId !== formData.association_id) {
      setFormData(prev => ({ ...prev, association_id: associationId }));
      setSelectedExpenseIds(new Set());
    }
  };

  const handleSubmit = async () => {
    if (!formData.name || !formData.association_id) {
      toast({ variant: "destructive", title: "Missing fields", description: "Name and Association are required." });
      return;
    }

    setLoading(true);
    try {
      let bundleId = bundle?.id;

      const bundlePayload = {
        name: formData.name,
        description: formData.description,
        client_id: formData.association_id,
        updated_at: new Date().toISOString()
      };

      if (bundleId) {
        const { error } = await supabase.from('expense_bundles').update(bundlePayload).eq('id', bundleId);
        if (error) throw error;
      } else {
        const { data, error } = await supabase
          .from('expense_bundles')
          .insert([{ ...bundlePayload, created_by: user?.id }])
          .select()
          .single();
        if (error) throw error;
        bundleId = data.id;
      }

      // Sync bundle expenses
      await supabase.from('bundle_expenses').delete().eq('bundle_id', bundleId);

      if (selectedExpenseIds.size > 0) {
        const links = Array.from(selectedExpenseIds).map((itemId) => {
          if (String(itemId).startsWith('fee:')) {
            return {
              bundle_id: bundleId,
              fee_schedule_id: String(itemId).replace('fee:', ''),
            };
          }

          return {
            bundle_id: bundleId,
            expense_id: itemId,
          };
        });

        const { error: linkError } = await supabase.from('bundle_expenses').insert(links);
        if (linkError) throw linkError;
      }

      toast({ title: "Success", description: `Bundle ${bundle ? 'updated' : 'created'} with ${selectedExpenseIds.size} items.` });
      onSuccess?.();
      onOpenChange(false);
    } catch (error) {
      console.error('Bundle save error:', error);
      toast({ variant: "destructive", title: "Error", description: error.message || "Failed to save bundle." });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="!flex !h-[calc(100vh-2rem)] !w-[calc(100vw-2rem)] !max-h-[calc(100vh-2rem)] !max-w-[1000px] !flex-col !gap-0 overflow-hidden p-0">
        <DialogHeader className="p-6 pb-2 shrink-0">
          <DialogTitle>{bundle ? 'Edit Expense Bundle' : 'Create Expense Bundle'}</DialogTitle>
          <DialogDescription>Group related expenses together for organized billing.</DialogDescription>
        </DialogHeader>

        <div className="flex-1 min-h-0 overflow-y-auto px-6 py-4 space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 p-4 bg-muted/50 border rounded-lg">
            <div className="space-y-4">
              <div className="space-y-2">
                <Label>Association</Label>
                <Select value={formData.association_id} onValueChange={handleAssociationChange} disabled={!!bundle}>
                  <SelectTrigger className="bg-background">
                    <SelectValue placeholder="Select Association" />
                  </SelectTrigger>
                  <SelectContent>
                    {associations.map(a => (
                      <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Bundle Name</Label>
                <Input
                  value={formData.name}
                  onChange={e => setFormData(prev => ({ ...prev, name: e.target.value }))}
                  placeholder="e.g. July 2024 Legal Fees"
                  className="bg-background"
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label>Description</Label>
              <Textarea
                value={formData.description}
                onChange={e => setFormData(prev => ({ ...prev, description: e.target.value }))}
                placeholder="Optional details about this bundle..."
                className="h-[108px] bg-background resize-none"
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label className="text-base font-semibold">Select Fees to Include</Label>
            {formData.association_id ? (
              <ExpenseBundleSelector
                associationId={formData.association_id}
                selectedIds={selectedExpenseIds}
                onSelectionChange={setSelectedExpenseIds}
              />
            ) : (
              <div className="p-12 text-center border-2 border-dashed rounded-lg text-muted-foreground bg-muted/30">
                Please select an association to view existing billable expenses and universal fee templates.
              </div>
            )}
          </div>
        </div>

        <DialogFooter className="shrink-0 border-t bg-background p-6 pt-2">
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={handleSubmit} disabled={loading || !formData.association_id} className="min-w-[140px]">
            {loading ? 'Saving...' : (bundle ? 'Update Bundle' : 'Create Bundle')}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
