import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Loader2, Save, DollarSign, Clock } from "lucide-react";

interface Props {
  associationId: string;
  associationName: string;
}

interface FeeRules {
  id?: string;
  interest_enabled: boolean;
  interest_rate: number;
  interest_grace_days: number;
  interest_compound: string;
  interest_apply_to: string;
  late_fee_enabled: boolean;
  late_fee_type: string;
  late_fee_amount: number;
  late_fee_trigger_days: number;
  late_fee_max: number | null;
  late_fee_recurring: boolean;
  auto_apply_enabled: boolean;
  auto_apply_schedule: string;
  auto_apply_day: number;
}

const DEFAULT_FEE_RULES: FeeRules = {
  interest_enabled: false,
  interest_rate: 0,
  interest_grace_days: 30,
  interest_compound: "monthly",
  interest_apply_to: "assessments",
  late_fee_enabled: false,
  late_fee_type: "flat",
  late_fee_amount: 0,
  late_fee_trigger_days: 15,
  late_fee_max: null,
  late_fee_recurring: false,
  auto_apply_enabled: false,
  auto_apply_schedule: "monthly",
  auto_apply_day: 1,
};

export default function FeesTab({ associationId, associationName }: Props) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [feeRules, setFeeRules] = useState<FeeRules>(DEFAULT_FEE_RULES);

  useEffect(() => {
    fetchFeeRules();
  }, [associationId]);

  const fetchFeeRules = async () => {
    setLoading(true);
    const { data } = await supabase
      .from("association_fee_rules")
      .select("*")
      .eq("association_id", associationId)
      .maybeSingle();
    if (data) setFeeRules({ ...DEFAULT_FEE_RULES, ...data });
    setLoading(false);
  };

  const saveFeeRules = async () => {
    setSaving(true);
    const payload = { ...feeRules, association_id: associationId };
    delete (payload as any).id;

    const { error } = feeRules.id
      ? await supabase.from("association_fee_rules").update(payload).eq("id", feeRules.id)
      : await supabase.from("association_fee_rules").insert(payload);

    if (error) {
      toast({ title: "Error saving fee rules", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "Fee rules saved" });
      fetchFeeRules();
    }
    setSaving(false);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* ── Interest & Late Fee Rules ── */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <DollarSign className="h-5 w-5 text-primary" />
            Interest & Late Fee Rules
          </CardTitle>
          <CardDescription>Configure how interest and late fees are calculated for {associationName}. These charges can be auto-applied to owner ledgers.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* Interest Section */}
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <h4 className="text-sm font-semibold">Interest Charges</h4>
                <p className="text-xs text-muted-foreground">Apply interest on outstanding balances</p>
              </div>
              <Switch
                checked={feeRules.interest_enabled}
                onCheckedChange={(v) => setFeeRules({ ...feeRules, interest_enabled: v })}
              />
            </div>
            {feeRules.interest_enabled && (
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 pl-4 border-l-2 border-primary/20">
                <div className="space-y-1.5">
                  <Label className="text-xs">APR Rate (%)</Label>
                  <Input
                    type="number"
                    step="0.01"
                    value={feeRules.interest_rate}
                    onChange={(e) => setFeeRules({ ...feeRules, interest_rate: Number(e.target.value) })}
                    className="text-sm"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">Grace Period (days)</Label>
                  <Input
                    type="number"
                    value={feeRules.interest_grace_days}
                    onChange={(e) => setFeeRules({ ...feeRules, interest_grace_days: Number(e.target.value) })}
                    className="text-sm"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">Compounding</Label>
                  <Select value={feeRules.interest_compound} onValueChange={(v) => setFeeRules({ ...feeRules, interest_compound: v })}>
                    <SelectTrigger className="text-sm"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="daily">Daily</SelectItem>
                      <SelectItem value="monthly">Monthly</SelectItem>
                      <SelectItem value="quarterly">Quarterly</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">Apply To</Label>
                  <Select value={feeRules.interest_apply_to} onValueChange={(v) => setFeeRules({ ...feeRules, interest_apply_to: v })}>
                    <SelectTrigger className="text-sm"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="assessments">Assessments Only</SelectItem>
                      <SelectItem value="assessments_and_fees">Assessments & Fees</SelectItem>
                      <SelectItem value="all_charges">All Charges</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            )}
          </div>

          <Separator />

          {/* Late Fee Section */}
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <h4 className="text-sm font-semibold">Late Fees</h4>
                <p className="text-xs text-muted-foreground">Charge late fees on overdue accounts</p>
              </div>
              <Switch
                checked={feeRules.late_fee_enabled}
                onCheckedChange={(v) => setFeeRules({ ...feeRules, late_fee_enabled: v })}
              />
            </div>
            {feeRules.late_fee_enabled && (
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 pl-4 border-l-2 border-primary/20">
                <div className="space-y-1.5">
                  <Label className="text-xs">Fee Type</Label>
                  <Select value={feeRules.late_fee_type} onValueChange={(v) => setFeeRules({ ...feeRules, late_fee_type: v })}>
                    <SelectTrigger className="text-sm"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="flat">Flat Amount ($)</SelectItem>
                      <SelectItem value="percentage">Percentage (%)</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">{feeRules.late_fee_type === "flat" ? "Amount ($)" : "Percentage (%)"}</Label>
                  <Input
                    type="number"
                    step="0.01"
                    value={feeRules.late_fee_amount}
                    onChange={(e) => setFeeRules({ ...feeRules, late_fee_amount: Number(e.target.value) })}
                    className="text-sm"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">Trigger (days past due)</Label>
                  <Input
                    type="number"
                    value={feeRules.late_fee_trigger_days}
                    onChange={(e) => setFeeRules({ ...feeRules, late_fee_trigger_days: Number(e.target.value) })}
                    className="text-sm"
                  />
                </div>
                {feeRules.late_fee_type === "percentage" && (
                  <div className="space-y-1.5">
                    <Label className="text-xs">Max Cap ($)</Label>
                    <Input
                      type="number"
                      step="0.01"
                      value={feeRules.late_fee_max ?? ""}
                      onChange={(e) => setFeeRules({ ...feeRules, late_fee_max: e.target.value ? Number(e.target.value) : null })}
                      className="text-sm"
                      placeholder="No cap"
                    />
                  </div>
                )}
                <div className="flex items-center gap-2 col-span-2">
                  <Switch
                    checked={feeRules.late_fee_recurring}
                    onCheckedChange={(v) => setFeeRules({ ...feeRules, late_fee_recurring: v })}
                  />
                  <Label className="text-xs">Apply every month while overdue</Label>
                </div>
              </div>
            )}
          </div>

          <Separator />

          {/* Auto-apply Schedule */}
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <h4 className="text-sm font-semibold flex items-center gap-2"><Clock className="h-4 w-4" /> Auto-Apply Schedule</h4>
                <p className="text-xs text-muted-foreground">Automatically generate interest and late fee charges</p>
              </div>
              <Switch
                checked={feeRules.auto_apply_enabled}
                onCheckedChange={(v) => setFeeRules({ ...feeRules, auto_apply_enabled: v })}
              />
            </div>
            {feeRules.auto_apply_enabled && (
              <div className="grid grid-cols-2 md:grid-cols-3 gap-4 pl-4 border-l-2 border-primary/20">
                <div className="space-y-1.5">
                  <Label className="text-xs">Frequency</Label>
                  <Select value={feeRules.auto_apply_schedule} onValueChange={(v) => setFeeRules({ ...feeRules, auto_apply_schedule: v })}>
                    <SelectTrigger className="text-sm"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="monthly">Monthly</SelectItem>
                      <SelectItem value="quarterly">Quarterly</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">Day of Month</Label>
                  <Input
                    type="number"
                    min={1}
                    max={28}
                    value={feeRules.auto_apply_day}
                    onChange={(e) => setFeeRules({ ...feeRules, auto_apply_day: Number(e.target.value) })}
                    className="text-sm"
                  />
                </div>
              </div>
            )}
          </div>

          <div className="flex justify-end">
            <Button onClick={saveFeeRules} disabled={saving} className="gap-2">
              {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
              Save Fee Rules
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
