import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { useToast } from "@/hooks/use-toast";
import { Edit2, Save, X, Plus, Trash2, ArrowRightLeft, Merge } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogDescription,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import MoveInOutDialog from "./MoveInOutDialog";

interface Owner {
  id: string;
  owner_type?: "individual" | "business";
  business_name?: string | null;
  management_company?: string | null;
  management_contact_name?: string | null;
  management_contact_title?: string | null;
  management_contact_email?: string | null;
  management_contact_phone?: string | null;
  first_name: string;
  last_name: string;
  email: string | null;
  phone: string | null;
  mailing_address: string | null;
  property_address: string | null;
  is_primary: boolean;
  isNew?: boolean;
}

interface OwnersTabProps {
  unitId: string;
  associationId?: string;
  onOwnersChange?: () => void;
}

export default function OwnersTab({ unitId, associationId, onOwnersChange }: OwnersTabProps) {
  const { toast } = useToast();
  const [isEditing, setIsEditing] = useState(false);
  const [owners, setOwners] = useState<Owner[]>([]);
  const [editForm, setEditForm] = useState<Owner[]>([]);
  const [moveDialogOpen, setMoveDialogOpen] = useState(false);
  const [resolvedAssocId, setResolvedAssocId] = useState(associationId || "");

  // Delete state
  const [deleteOwner, setDeleteOwner] = useState<Owner | null>(null);

  // Merge state
  const [selectedForMerge, setSelectedForMerge] = useState<Set<string>>(new Set());
  const [mergeDialogOpen, setMergeDialogOpen] = useState(false);
  const [primaryMergeId, setPrimaryMergeId] = useState("");

  useEffect(() => {
    if (unitId) {
      fetchOwners();
      if (!associationId) {
        supabase.from("units").select("association_id").eq("id", unitId).single().then(({ data }) => {
          if (data) setResolvedAssocId(data.association_id);
        });
      }
    }
  }, [unitId, associationId]);

  const fetchOwners = async () => {
    const { data } = await supabase
      .from("owners")
      .select("*")
      .eq("unit_id", unitId)
      .eq("status", "active")
      .order("is_primary", { ascending: false })
      .order("last_name", { ascending: true });
    if (data) setOwners(data.map(o => ({
      ...o,
      owner_type: o.owner_type === "business" ? "business" : "individual",
      business_name: o.business_name ?? "",
      management_company: o.management_company ?? "",
      management_contact_name: o.management_contact_name ?? "",
      management_contact_title: o.management_contact_title ?? "",
      management_contact_email: o.management_contact_email ?? "",
      management_contact_phone: o.management_contact_phone ?? "",
      email: o.email ?? "",
      phone: o.phone ?? "",
      mailing_address: o.mailing_address ?? "",
      property_address: o.property_address ?? "",
      is_primary: o.is_primary ?? false,
    })));
  };

  const handleEditClick = () => {
    setEditForm([...owners]);
    setIsEditing(true);
  };

  const handleCancel = () => {
    setIsEditing(false);
    setEditForm([]);
  };

  const handleAddOwner = () => {
    setEditForm([...editForm, {
      id: `temp-${Date.now()}`,
      owner_type: owners.some((owner) => owner.owner_type === "business") ? "business" : "individual",
      business_name: "", management_company: "", management_contact_name: "", management_contact_title: "", management_contact_email: "", management_contact_phone: "",
      first_name: "", last_name: "", email: "", phone: "",
      mailing_address: "", property_address: "", is_primary: false, isNew: true,
    }]);
  };

  const handleRemoveOwner = (index: number) => {
    setEditForm(editForm.filter((_, i) => i !== index));
  };

  const handleChange = (index: number, field: string, value: string) => {
    const updated = [...editForm];
    (updated[index] as any)[field] = value;
    setEditForm(updated);
  };

  const handleSave = async () => {
    const invalid = editForm.some(o => o.owner_type === "business" ? !((o.business_name || o.first_name).trim()) : (!o.first_name || !o.last_name));
    if (invalid) {
      toast({ title: "Validation Error", description: "A contact name or organization name is required.", variant: "destructive" });
      return;
    }

    try {
      for (const owner of editForm) {
        if (owner.isNew) {
          const { data: unit } = await supabase.from("units").select("association_id, unit_number").eq("id", unitId).single();
          if (unit) {
            // Auto-generate account number based on unit number
            const now = new Date();
            const yy = String(now.getFullYear()).slice(-2);
            const mm = String(now.getMonth() + 1).padStart(2, "0");
            const rand = String(Math.floor(Math.random() * 100)).padStart(2, "0");
            const acctNum = `${unit.unit_number || unitId.slice(0, 6)}-${yy}${mm}-${rand}`;
            
            await supabase.from("owners").insert({
              unit_id: unitId,
              association_id: unit.association_id,
              account_number: acctNum,
              owner_type: owner.owner_type || "individual",
              business_name: owner.owner_type === "business" ? (owner.business_name || owner.first_name) : null,
              management_company: owner.management_company || null,
              management_contact_name: owner.management_contact_name || null,
              management_contact_title: owner.management_contact_title || null,
              management_contact_email: owner.management_contact_email || null,
              management_contact_phone: owner.management_contact_phone || null,
              first_name: owner.first_name,
              last_name: owner.last_name,
              email: owner.management_contact_email || owner.email || null,
              phone: owner.management_contact_phone || owner.phone || null,
              mailing_address: owner.mailing_address || null,
              property_address: owner.property_address || null,
            });
          }
        } else {
          await supabase.from("owners").update({
            owner_type: owner.owner_type || "individual",
            business_name: owner.owner_type === "business" ? (owner.business_name || owner.first_name) : null,
            management_company: owner.management_company || null,
            management_contact_name: owner.management_contact_name || null,
            management_contact_title: owner.management_contact_title || null,
            management_contact_email: owner.management_contact_email || null,
            management_contact_phone: owner.management_contact_phone || null,
            first_name: owner.first_name,
            last_name: owner.last_name,
            email: owner.management_contact_email || owner.email || null,
            phone: owner.management_contact_phone || owner.phone || null,
            mailing_address: owner.mailing_address || null,
            property_address: owner.property_address || null,
          }).eq("id", owner.id);
        }
      }
      await fetchOwners();
      onOwnersChange?.();
      setIsEditing(false);
      toast({ title: "Success", description: "Contacts updated." });
    } catch (error) {
      console.error(error);
      toast({ title: "Error", description: "Failed to update contacts.", variant: "destructive" });
    }
  };

  // Delete handler
  const handleDeleteConfirm = async () => {
    if (!deleteOwner) return;
    try {
      // Delete linked deposit_batch_items first
      await supabase.from("deposit_batch_items" as any).delete().eq("owner_id", deleteOwner.id);
      const { error } = await supabase.from("owners").delete().eq("id", deleteOwner.id);
      if (error) throw error;
      toast({ title: "Owner deleted" });
      setDeleteOwner(null);
      await fetchOwners();
      onOwnersChange?.();
    } catch (err: any) {
      toast({ variant: "destructive", title: "Error", description: err.message });
    }
  };

  // Merge handlers
  const toggleMergeSelection = (id: string) => {
    setSelectedForMerge(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  };

  const openMergeDialog = () => {
    if (selectedForMerge.size < 2) {
      toast({ variant: "destructive", title: "Select at least 2 owners to merge" });
      return;
    }
    const ids = Array.from(selectedForMerge);
    setPrimaryMergeId(ids[0]);
    setMergeDialogOpen(true);
  };

  const handleMergeConfirm = async () => {
    const secondaryIds = Array.from(selectedForMerge).filter(id => id !== primaryMergeId);
    if (!primaryMergeId || secondaryIds.length === 0) return;

    try {
      // Re-assign related records from secondary owners to primary
      for (const secId of secondaryIds) {
        await supabase.from("owner_ledger_entries").update({ owner_id: primaryMergeId } as any).eq("owner_id", secId);
        await supabase.from("admin_payments").update({ owner_id: primaryMergeId } as any).eq("owner_id", secId);
        await supabase.from("collections").update({ owner_id: primaryMergeId } as any).eq("owner_id", secId);
        await supabase.from("violations").update({ owner_id: primaryMergeId } as any).eq("owner_id", secId);
        // Delete the secondary owner
        await supabase.from("deposit_batch_items" as any).delete().eq("owner_id", secId);
        await supabase.from("owners").delete().eq("id", secId);
      }

      toast({ title: "Owners merged", description: `${secondaryIds.length} owner(s) merged into the primary record.` });
      setMergeDialogOpen(false);
      setSelectedForMerge(new Set());
      await fetchOwners();
      onOwnersChange?.();
    } catch (err: any) {
      toast({ variant: "destructive", title: "Merge failed", description: err.message });
    }
  };

  const mergeOwners = owners.filter(o => selectedForMerge.has(o.id));
  const hasOrganizationOwners = owners.some((owner) => owner.owner_type === "business") || editForm.some((owner) => owner.owner_type === "business");
  const primaryOrganizationContact = owners.find((owner) => owner.owner_type === "business" && (owner.management_contact_name || owner.is_primary)) || owners.find((owner) => owner.is_primary) || owners[0];

  return (
    <>
      <Card className="border-border shadow-sm rounded-xl">
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle className="text-lg">{hasOrganizationOwners ? "Organization Contacts" : "Property Owners"}</CardTitle>
          <div className="flex gap-2">
            {!isEditing ? (
              <>
                {selectedForMerge.size >= 2 && (
                  <Button variant="outline" size="sm" onClick={openMergeDialog}>
                    <Merge className="w-4 h-4 mr-2" /> Merge ({selectedForMerge.size})
                  </Button>
                )}
                <Button variant="outline" size="sm" onClick={() => setMoveDialogOpen(true)}>
                  <ArrowRightLeft className="w-4 h-4 mr-2" /> Move In/Out
                </Button>
                  <Button variant="outline" size="sm" onClick={handleEditClick}>
                  <Edit2 className="w-4 h-4 mr-2" /> {hasOrganizationOwners ? "Edit Contacts" : "Edit Owners"}
                </Button>
              </>
            ) : (
              <>
                <Button variant="ghost" size="sm" onClick={handleCancel}><X className="w-4 h-4 mr-2" /> Cancel</Button>
                <Button size="sm" onClick={handleSave}><Save className="w-4 h-4 mr-2" /> Save</Button>
              </>
            )}
          </div>
        </CardHeader>
        <CardContent className="p-0">
            <div className="p-4">
              <Tabs defaultValue="contacts" className="space-y-4">
                <TabsList>
                  <TabsTrigger value="contacts">{hasOrganizationOwners ? "Contacts" : "Owners"}</TabsTrigger>
                  <TabsTrigger value="primary">{hasOrganizationOwners ? "Primary Contact" : "Primary Owner"}</TabsTrigger>
                </TabsList>
                <TabsContent value="primary" className="rounded-md border border-border p-4">
                  {primaryOrganizationContact ? (
                    <div className="space-y-2">
                      <div className="flex flex-wrap items-center gap-2">
                        <h3 className="font-semibold text-foreground">{primaryOrganizationContact.management_contact_name || `${primaryOrganizationContact.first_name} ${primaryOrganizationContact.last_name}`}</h3>
                        <Badge variant="secondary">Primary</Badge>
                      </div>
                      <div className="text-sm text-muted-foreground">{primaryOrganizationContact.management_contact_title || "Primary contact"}</div>
                      <div className="grid gap-2 text-sm sm:grid-cols-2">
                        <div>{primaryOrganizationContact.management_contact_email || primaryOrganizationContact.email || "No email"}</div>
                        <div>{primaryOrganizationContact.management_contact_phone || primaryOrganizationContact.phone || "No phone"}</div>
                        <div className="sm:col-span-2">Organization: {primaryOrganizationContact.business_name || primaryOrganizationContact.first_name}</div>
                        {primaryOrganizationContact.management_company && <div className="sm:col-span-2">Management: {primaryOrganizationContact.management_company}</div>}
                      </div>
                    </div>
                  ) : <p className="text-sm text-muted-foreground">No primary {hasOrganizationOwners ? "contact" : "owner"} recorded.</p>}
                </TabsContent>
                <TabsContent value="contacts" className="mt-0">
          <Table>
            <TableHeader>
              <TableRow>
                {!isEditing && owners.length > 1 && <TableHead className="w-10">Merge</TableHead>}
                <TableHead>{hasOrganizationOwners ? "Contact / Organization" : "Name"}</TableHead>
                {hasOrganizationOwners && <TableHead>Title</TableHead>}
                <TableHead>Email</TableHead>
                <TableHead>Phone</TableHead>
                <TableHead>Property Address</TableHead>
                <TableHead>Mailing Address</TableHead>
                <TableHead className="text-right">Action</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isEditing ? (
                editForm.map((owner, index) => (
                  <TableRow key={owner.id}>
                    <TableCell className="space-y-2">
                      {hasOrganizationOwners ? (
                        <>
                          <Input value={owner.business_name ?? ""} onChange={e => handleChange(index, "business_name", e.target.value)} placeholder="Organization name *" />
                          <Input value={owner.management_contact_name ?? ""} onChange={e => handleChange(index, "management_contact_name", e.target.value)} placeholder="Contact name" />
                        </>
                      ) : (
                        <>
                          <Input value={owner.first_name} onChange={e => handleChange(index, "first_name", e.target.value)} placeholder="First name *" />
                          <Input value={owner.last_name} onChange={e => handleChange(index, "last_name", e.target.value)} placeholder="Last name *" />
                        </>
                      )}
                    </TableCell>
                    {hasOrganizationOwners && <TableCell><Input value={owner.management_contact_title ?? ""} onChange={e => handleChange(index, "management_contact_title", e.target.value)} placeholder="Title" /></TableCell>}
                    <TableCell>
                      <Input value={(hasOrganizationOwners ? owner.management_contact_email : owner.email) ?? ""} onChange={e => handleChange(index, hasOrganizationOwners ? "management_contact_email" : "email", e.target.value)} placeholder="Email" type="email" />
                    </TableCell>
                    <TableCell>
                      <Input value={(hasOrganizationOwners ? owner.management_contact_phone : owner.phone) ?? ""} onChange={e => handleChange(index, hasOrganizationOwners ? "management_contact_phone" : "phone", e.target.value)} placeholder="Phone" />
                    </TableCell>
                    <TableCell>
                      <Input value={owner.property_address ?? ""} onChange={e => handleChange(index, "property_address", e.target.value)} placeholder="Property address" />
                    </TableCell>
                    <TableCell>
                      <Input value={owner.mailing_address ?? ""} onChange={e => handleChange(index, "mailing_address", e.target.value)} placeholder="Mailing address" />
                    </TableCell>
                    <TableCell className="text-right">
                      <Button variant="ghost" size="sm" onClick={() => handleRemoveOwner(index)} className="text-destructive hover:text-destructive">
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                owners.length === 0 ? (
                  <TableRow><TableCell colSpan={7} className="text-center text-muted-foreground py-8">No owners recorded.</TableCell></TableRow>
                ) : (
                  owners.map(owner => (
                    <TableRow key={owner.id}>
                      {owners.length > 1 && (
                        <TableCell>
                          <Checkbox
                            checked={selectedForMerge.has(owner.id)}
                            onCheckedChange={() => toggleMergeSelection(owner.id)}
                          />
                        </TableCell>
                      )}
                      <TableCell className="font-medium text-primary whitespace-nowrap">
                        {owner.owner_type === "business" ? (owner.business_name || owner.first_name) : `${owner.first_name} ${owner.last_name}`}
                        {owner.is_primary && (
                          <span className="ml-2 text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary">Primary</span>
                        )}
                        {owner.owner_type === "business" && owner.management_contact_name && <div className="text-xs font-normal text-muted-foreground">{owner.management_contact_name}</div>}
                      </TableCell>
                      {hasOrganizationOwners && <TableCell className="text-sm text-muted-foreground">{owner.management_contact_title || "—"}</TableCell>}
                      <TableCell className="text-sm">{owner.management_contact_email || owner.email || "—"}</TableCell>
                      <TableCell className="text-sm text-muted-foreground">{owner.management_contact_phone || owner.phone || "—"}</TableCell>
                      <TableCell className="text-sm text-muted-foreground max-w-[200px] truncate" title={owner.property_address || ""}>
                        {owner.property_address || "—"}
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground max-w-[200px] truncate" title={owner.mailing_address || ""}>
                        {owner.mailing_address || "—"}
                      </TableCell>
                      <TableCell className="text-right">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => setDeleteOwner(owner)}
                          className="text-destructive hover:text-destructive"
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )
              )}
            </TableBody>
          </Table>
          {isEditing && (
            <div className="p-4 border-t bg-muted/50">
              <Button variant="outline" size="sm" onClick={handleAddOwner} className="w-full border-dashed">
                <Plus className="w-4 h-4 mr-2" /> {hasOrganizationOwners ? "Add Additional Contact" : "Add Additional Owner"}
              </Button>
            </div>
          )}
                </TabsContent>
              </Tabs>
            </div>
        </CardContent>
      </Card>

      <MoveInOutDialog
        open={moveDialogOpen}
        onOpenChange={setMoveDialogOpen}
        unitId={unitId}
        associationId={resolvedAssocId}
        currentOwners={owners}
        onComplete={() => { fetchOwners(); onOwnersChange?.(); }}
      />

      {/* Delete Confirmation */}
      <AlertDialog open={!!deleteOwner} onOpenChange={(open) => !open && setDeleteOwner(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Owner</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to permanently delete{" "}
              <strong>{deleteOwner?.first_name} {deleteOwner?.last_name}</strong>?
              This will also remove linked records. This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={handleDeleteConfirm} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Merge Dialog */}
      <Dialog open={mergeDialogOpen} onOpenChange={setMergeDialogOpen}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle>Merge Owners</DialogTitle>
            <DialogDescription>
              Select the primary owner to keep. The other owner records will be deleted and their ledger entries, payments, collections, and violations will be reassigned to the primary.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3 py-4">
            <Label className="font-semibold">Keep as primary:</Label>
            <RadioGroup value={primaryMergeId} onValueChange={setPrimaryMergeId}>
              {mergeOwners.map(o => (
                <div key={o.id} className="flex items-start gap-3 p-3 rounded-lg border border-border">
                  <RadioGroupItem value={o.id} id={`merge-${o.id}`} className="mt-0.5" />
                  <label htmlFor={`merge-${o.id}`} className="flex-1 cursor-pointer">
                    <div className="font-medium">{o.first_name} {o.last_name}</div>
                    <div className="text-xs text-muted-foreground">{o.email || "No email"}</div>
                    <div className="text-xs text-muted-foreground">{o.mailing_address || o.property_address || "No address"}</div>
                  </label>
                </div>
              ))}
            </RadioGroup>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setMergeDialogOpen(false)}>Cancel</Button>
            <Button onClick={handleMergeConfirm}>Merge Owners</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
