import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import { useToast } from "@/hooks/use-toast";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { Ban, Pencil, Plus, ShieldOff, Trash2 } from "lucide-react";

type FeeType = "late_fee" | "interest";
type Mode = "waive" | "override_amount" | "override_percent";

interface Exclusion {
  id: string;
  association_id: string;
  unit_id: string;
  fee_type: FeeType;
  mode: Mode;
  override_amount: number | null;
  override_percent: number | null;
  reason: string | null;
  created_at: string;
}

interface Props {
  unitId: string;
  associationId: string;
  canEdit?: boolean;
}

const FEE_LABEL: Record<FeeType, string> = {
  late_fee: "Late Fee",
  interest: "Interest",
};

export default function UnitFeeExclusionsCard({ unitId, associationId, canEdit = true }: Props) {
  const { user } = useAuth();
  const { toast } = useToast();
  const [items, setItems] = useState<Exclusion[]>([]);
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<Exclusion | null>(null);

  const [feeType, setFeeType] = useState<FeeType>("late_fee");
  const [mode, setMode] = useState<Mode>("waive");
  const [overrideAmount, setOverrideAmount] = useState("");
  const [overridePercent, setOverridePercent] = useState("");
  const [reason, setReason] = useState("");
  const [saving, setSaving] = useState(false);

  const fetchItems = async () => {
    setLoading(true);
    const { data, error } = await supabase
      .from("unit_fee_exclusions")
      .select("*")
      .eq("unit_id", unitId)
      .order("fee_type");
    if (error) {
      toast({ variant: "destructive", title: "Error", description: error.message });
    } else {
      setItems((data || []) as Exclusion[]);
    }
    setLoading(false);
  };

  useEffect(() => {
    if (unitId) fetchItems();
  }, [unitId]);

  const openNew = () => {
    setEditing(null);
    setFeeType("late_fee");
    setMode("waive");
    setOverrideAmount("");
    setOverridePercent("");
    setReason("");
    setDialogOpen(true);
  };

  const openEdit = (item: Exclusion) => {
    setEditing(item);
    setFeeType(item.fee_type);
    setMode(item.mode);
    setOverrideAmount(item.override_amount != null ? String(item.override_amount) : "");
    setOverridePercent(item.override_percent != null ? String(Number(item.override_percent) * 100) : "");
    setReason(item.reason || "");
    setDialogOpen(true);
  };

  const handleSave = async () => {
    if (mode === "override_amount") {
      const amt = parseFloat(overrideAmount);
      if (isNaN(amt) || amt < 0) {
        toast({
          variant: "destructive",
          title: "Invalid amount",
          description: "Enter a valid override amount (0 or greater).",
        });
        return;
      }
    }
    if (mode === "override_percent") {
      const pct = parseFloat(overridePercent);
      if (isNaN(pct) || pct < 0) {
        toast({
          variant: "destructive",
          title: "Invalid rate",
          description: "Enter a valid percentage (e.g. 1.5 for 1.5%).",
        });
        return;
      }
    }

    setSaving(true);
    const payload = {
      association_id: associationId,
      unit_id: unitId,
      fee_type: feeType,
      mode,
      override_amount: mode === "override_amount" ? parseFloat(overrideAmount) : null,
      override_percent: mode === "override_percent" ? parseFloat(overridePercent) / 100 : null,
      reason: reason.trim() || null,
      created_by: user?.id || null,
    };

    let error;
    if (editing) {
      ({ error } = await supabase
        .from("unit_fee_exclusions")
        .update(payload)
        .eq("id", editing.id));
    } else {
      ({ error } = await supabase.from("unit_fee_exclusions").insert([payload]));
    }
    setSaving(false);

    if (error) {
      const msg = error.message.includes("duplicate")
        ? `An exclusion for ${FEE_LABEL[feeType]} already exists on this unit.`
        : error.message;
      toast({ variant: "destructive", title: "Error", description: msg });
      return;
    }
    toast({ title: "Saved", description: "Fee exclusion saved." });
    setDialogOpen(false);
    fetchItems();
  };

  const handleDelete = async (item: Exclusion) => {
    if (!confirm(`Remove ${FEE_LABEL[item.fee_type]} exclusion for this unit?`)) return;
    const { error } = await supabase.from("unit_fee_exclusions").delete().eq("id", item.id);
    if (error) {
      toast({ variant: "destructive", title: "Error", description: error.message });
    } else {
      toast({ title: "Removed" });
      fetchItems();
    }
  };

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-3">
        <div className="flex items-center gap-2">
          <ShieldOff className="w-4 h-4 text-muted-foreground" />
          <CardTitle className="text-base">Fee Exclusions</CardTitle>
        </div>
        {canEdit && (
          <Button size="sm" variant="outline" onClick={openNew}>
            <Plus className="w-4 h-4 mr-1" /> Add Exclusion
          </Button>
        )}
      </CardHeader>
      <CardContent>
        {loading ? (
          <p className="text-sm text-muted-foreground">Loading…</p>
        ) : items.length === 0 ? (
          <p className="text-sm text-muted-foreground">
            No exclusions. Late fees and interest will apply normally.
          </p>
        ) : (
          <ul className="space-y-2">
            {items.map((item) => (
              <li
                key={item.id}
                className="flex items-start justify-between gap-3 p-3 rounded-md border border-border bg-muted/30"
              >
                <div className="flex-1 min-w-0">
                  <div className="flex flex-wrap items-center gap-2">
                    <Badge variant="secondary">{FEE_LABEL[item.fee_type]}</Badge>
                    {item.mode === "waive" ? (
                      <Badge variant="destructive" className="gap-1">
                        <Ban className="w-3 h-3" /> Waived
                      </Badge>
                    ) : item.mode === "override_percent" ? (
                      <Badge>Override Rate: {(Number(item.override_percent || 0) * 100).toFixed(4).replace(/\.?0+$/, "")}%</Badge>
                    ) : (
                      <Badge>Override: ${Number(item.override_amount || 0).toFixed(2)}</Badge>
                    )}
                  </div>
                  {item.reason && (
                    <p className="mt-1 text-xs text-muted-foreground">{item.reason}</p>
                  )}
                </div>
                {canEdit && (
                  <div className="flex items-center gap-1">
                    <Button size="icon" variant="ghost" onClick={() => openEdit(item)}>
                      <Pencil className="w-4 h-4" />
                    </Button>
                    <Button size="icon" variant="ghost" onClick={() => handleDelete(item)}>
                      <Trash2 className="w-4 h-4 text-destructive" />
                    </Button>
                  </div>
                )}
              </li>
            ))}
          </ul>
        )}
      </CardContent>

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{editing ? "Edit" : "Add"} Fee Exclusion</DialogTitle>
            <DialogDescription>
              Waive a fee entirely, override it to a fixed amount, or — for interest — apply a
              custom percentage rate whenever it would be charged to this unit.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-2">
            <div className="space-y-2">
              <Label>Fee Type</Label>
              <Select
                value={feeType}
                onValueChange={(v) => {
                  setFeeType(v as FeeType);
                  if (v !== "interest" && mode === "override_percent") setMode("waive");
                }}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="late_fee">Late Fee</SelectItem>
                  <SelectItem value="interest">Interest</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>Action</Label>
              <Select value={mode} onValueChange={(v) => setMode(v as Mode)}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="waive">Waive entirely (skip charge)</SelectItem>
                  <SelectItem value="override_amount">Override to specific amount</SelectItem>
                  {feeType === "interest" && (
                    <SelectItem value="override_percent">Override to specific % rate</SelectItem>
                  )}
                </SelectContent>
              </Select>
            </div>

            {mode === "override_amount" && (
              <div className="space-y-2">
                <Label>Override Amount ($)</Label>
                <Input
                  type="number"
                  step="0.01"
                  min="0"
                  value={overrideAmount}
                  onChange={(e) => setOverrideAmount(e.target.value)}
                  placeholder="0.00"
                />
                <p className="text-xs text-muted-foreground">
                  This exact amount will be charged instead of the calculated fee.
                </p>
              </div>
            )}

            {mode === "override_percent" && (
              <div className="space-y-2">
                <Label>Override Rate (%)</Label>
                <Input
                  type="number"
                  step="0.0001"
                  min="0"
                  value={overridePercent}
                  onChange={(e) => setOverridePercent(e.target.value)}
                  placeholder="e.g. 1.5"
                />
                <p className="text-xs text-muted-foreground">
                  This rate will replace the association's standard interest rate for this unit
                  (e.g. enter 1.5 for 1.5% per period).
                </p>
              </div>
            )}

            <div className="space-y-2">
              <Label>Reason (optional)</Label>
              <Input
                value={reason}
                onChange={(e) => setReason(e.target.value)}
                placeholder="e.g. Board approved hardship waiver"
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setDialogOpen(false)}>
              Cancel
            </Button>
            <Button onClick={handleSave} disabled={saving}>
              {saving ? "Saving…" : "Save"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </Card>
  );
}
