import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { useToast } from "@/hooks/use-toast";
import { Plus, Trash2, ArrowRightLeft, Loader2, AlertTriangle } from "lucide-react";
import { Checkbox } from "@/components/ui/checkbox";

interface CurrentOwner {
  id: string;
  first_name: string;
  last_name: string;
  email: string | null;
}

interface NewOwnerForm {
  key: string;
  first_name: string;
  last_name: string;
  email: string;
  phone: string;
  mailing_address: string;
  is_primary: boolean;
}

interface MoveInOutDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  unitId: string;
  associationId: string;
  currentOwners: CurrentOwner[];
  onComplete: () => void;
}

const emptyOwner = (): NewOwnerForm => ({
  key: `new-${Date.now()}-${Math.random()}`,
  first_name: "",
  last_name: "",
  email: "",
  phone: "",
  mailing_address: "",
  is_primary: false,
});

const generateAccountNumber = (unitNumber: string, index: number): string => {
  const now = new Date();
  const yy = String(now.getFullYear()).slice(-2);
  const mm = String(now.getMonth() + 1).padStart(2, "0");
  const seq = String(index + 1).padStart(2, "0");
  return `${unitNumber}-${yy}${mm}-${seq}`;
};

export default function MoveInOutDialog({
  open,
  onOpenChange,
  unitId,
  associationId,
  currentOwners,
  onComplete,
}: MoveInOutDialogProps) {
  const { toast } = useToast();
  const [saving, setSaving] = useState(false);
  const [unitNumber, setUnitNumber] = useState("");
  const [newOwners, setNewOwners] = useState<NewOwnerForm[]>([{ ...emptyOwner(), is_primary: true }]);
  const [moveOutDate] = useState(() => new Date().toISOString().split("T")[0]);

  // Fetch unit number for account number generation
  useEffect(() => {
    if (!unitId) return;
    supabase.from("units").select("unit_number").eq("id", unitId).single()
      .then(({ data }) => { if (data) setUnitNumber(data.unit_number || ""); });
  }, [unitId]);

  const updateField = (index: number, field: keyof NewOwnerForm, value: string | boolean) => {
    setNewOwners((prev) => {
      const copy = [...prev];
      if (field === "is_primary" && value === true) {
        copy.forEach((o, i) => (o.is_primary = i === index));
      } else {
        (copy[index] as any)[field] = value;
      }
      return copy;
    });
  };

  const addOwner = () => setNewOwners((prev) => [...prev, emptyOwner()]);

  const removeOwner = (index: number) => {
    if (newOwners.length <= 1) return;
    setNewOwners((prev) => {
      const copy = prev.filter((_, i) => i !== index);
      if (!copy.some((o) => o.is_primary)) copy[0].is_primary = true;
      return copy;
    });
  };

  const handleSubmit = async () => {
    const invalid = newOwners.some((o) => !o.first_name.trim() || !o.last_name.trim());
    if (invalid) {
      toast({ title: "Validation Error", description: "First and last name are required for all new owners.", variant: "destructive" });
      return;
    }

    setSaving(true);
    try {
      const today = new Date().toISOString().split("T")[0];

      // 1. Insert a Move-Out marker on each current owner's ledger BEFORE archiving
      if (currentOwners.length > 0) {
        const moveOutMarkers = currentOwners.map((o) => ({
          unit_id: unitId,
          association_id: associationId,
          owner_id: o.id,
          date: today,
          transaction_type: "move_out",
          description: `Move-Out: ${o.first_name} ${o.last_name} archived as of ${today}`,
          debit: 0,
          credit: 0,
        }));
        const { error: markerErr } = await supabase.from("owner_ledger_entries").insert(moveOutMarkers);
        if (markerErr) console.warn("Move-out marker insert failed:", markerErr);

        // 2. Archive all current owners (move out)
        const ids = currentOwners.map((o) => o.id);
        const { error: archiveErr } = await supabase
          .from("owners")
          .update({ status: "archived" } as any)
          .in("id", ids);
        if (archiveErr) throw archiveErr;
      }

      // 3. Insert new owners (move in) with auto-generated account numbers
      const inserts = newOwners.map((o, i) => ({
        unit_id: unitId,
        association_id: associationId,
        account_number: generateAccountNumber(unitNumber || unitId.slice(0, 6), i),
        first_name: o.first_name.trim(),
        last_name: o.last_name.trim(),
        email: o.email.trim() || null,
        phone: o.phone.trim() || null,
        mailing_address: o.mailing_address.trim() || null,
        is_primary: o.is_primary,
        status: "active",
      }));

      const { data: insertedOwners, error: insertErr } = await supabase
        .from("owners")
        .insert(inserts)
        .select("id, first_name, last_name, is_primary");
      if (insertErr) throw insertErr;

      // 4. Insert a Move-In marker on the new primary owner's ledger
      const primaryNew = (insertedOwners || []).find((o: any) => o.is_primary) || (insertedOwners || [])[0];
      if (primaryNew) {
        const names = (insertedOwners || []).map((o: any) => `${o.first_name} ${o.last_name}`).join(", ");
        const { error: moveInErr } = await supabase.from("owner_ledger_entries").insert([{
          unit_id: unitId,
          association_id: associationId,
          owner_id: primaryNew.id,
          date: today,
          transaction_type: "move_in",
          description: `Move-In: ${names} as of ${today}`,
          debit: 0,
          credit: 0,
        }]);
        if (moveInErr) console.warn("Move-in marker insert failed:", moveInErr);
      }

      toast({ title: "Move In/Out Complete", description: `${currentOwners.length} owner(s) moved out, ${newOwners.length} new owner(s) moved in.` });
      onComplete();
      onOpenChange(false);
      setNewOwners([{ ...emptyOwner(), is_primary: true }]);
    } catch (err: any) {
      console.error(err);
      toast({ title: "Error", description: err.message || "Failed to process move in/out.", variant: "destructive" });
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <ArrowRightLeft className="h-5 w-5 text-primary" />
            Move In / Move Out
          </DialogTitle>
          <DialogDescription>
            Archive current owners and register new owners for this unit.
          </DialogDescription>
        </DialogHeader>

        {/* Move Out Section */}
        {currentOwners.length > 0 && (
          <div className="space-y-2">
            <Label className="text-sm font-semibold text-destructive flex items-center gap-1.5">
              <AlertTriangle className="h-3.5 w-3.5" />
              Moving Out ({currentOwners.length})
            </Label>
            <div className="rounded-lg border border-destructive/20 bg-destructive/5 p-3 space-y-1">
              {currentOwners.map((o) => (
                <div key={o.id} className="flex items-center justify-between text-sm">
                  <span className="font-medium">{o.first_name} {o.last_name}</span>
                  <span className="text-muted-foreground text-xs">{o.email || "No email"}</span>
                </div>
              ))}
              <p className="text-xs text-muted-foreground pt-1">
                These owners will be archived as of {moveOutDate}.
              </p>
            </div>
          </div>
        )}

        <Separator />

        {/* Move In Section */}
        <div className="space-y-3">
          <Label className="text-sm font-semibold text-primary">New Owners (Moving In)</Label>

          {newOwners.map((owner, index) => (
            <div key={owner.key} className="rounded-lg border bg-card p-4 space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium text-muted-foreground">Owner {index + 1}</span>
                <div className="flex items-center gap-3">
                  <label className="flex items-center gap-1.5 text-xs cursor-pointer">
                    <Checkbox
                      checked={owner.is_primary}
                      onCheckedChange={(v) => updateField(index, "is_primary", !!v)}
                    />
                    Primary
                  </label>
                  {newOwners.length > 1 && (
                    <Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => removeOwner(index)}>
                      <Trash2 className="h-3.5 w-3.5" />
                    </Button>
                  )}
                </div>
              </div>

              <div>
                <Label className="text-xs text-muted-foreground">Account Number</Label>
                <p className="text-sm font-mono mt-1 px-3 py-2 bg-muted rounded-md">{generateAccountNumber(unitNumber || "—", index)}</p>
                <p className="text-xs text-muted-foreground mt-1">Auto-generated based on unit number</p>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <Label className="text-xs">First Name *</Label>
                  <Input value={owner.first_name} onChange={(e) => updateField(index, "first_name", e.target.value)} placeholder="First name" />
                </div>
                <div>
                  <Label className="text-xs">Last Name *</Label>
                  <Input value={owner.last_name} onChange={(e) => updateField(index, "last_name", e.target.value)} placeholder="Last name" />
                </div>
                <div>
                  <Label className="text-xs">Email</Label>
                  <Input value={owner.email} onChange={(e) => updateField(index, "email", e.target.value)} placeholder="email@example.com" type="email" />
                </div>
                <div>
                  <Label className="text-xs">Phone</Label>
                  <Input value={owner.phone} onChange={(e) => updateField(index, "phone", e.target.value)} placeholder="(555) 555-5555" />
                </div>
              </div>
              <div>
                <Label className="text-xs">Mailing Address</Label>
                <Input value={owner.mailing_address} onChange={(e) => updateField(index, "mailing_address", e.target.value)} placeholder="123 Main St, City, ST 12345" />
              </div>
            </div>
          ))}

          <Button variant="outline" size="sm" className="w-full border-dashed" onClick={addOwner}>
            <Plus className="h-4 w-4 mr-2" /> Add Another Owner
          </Button>
        </div>

        <DialogFooter className="pt-2">
          <Button variant="ghost" onClick={() => onOpenChange(false)} disabled={saving}>Cancel</Button>
          <Button onClick={handleSubmit} disabled={saving}>
            {saving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
            Confirm Move In/Out
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
