import { useEffect, useState } from "react";
import { useParams, useNavigate, Link } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ArrowLeft, Home, Users, KeyRound, AlertTriangle, FileText, Settings, History, MessageSquare, PenTool, ImagePlus, Check, X, BarChart3, Play, RefreshCw, ArrowUpDown, FolderOpen, Clock } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import PropertyImage from "@/components/PropertyImage";
import OwnersTab from "@/components/unit-profile/OwnersTab";
import TenantsTab from "@/components/unit-profile/TenantsTab";
import UnitViolationsTab from "@/components/unit-profile/UnitViolationsTab";
import UnitArcApplicationsTab from "@/components/unit-profile/UnitArcApplicationsTab";
import UnitOwnerUpdatesTab from "@/components/unit-profile/UnitOwnerUpdatesTab";
import OtherTab from "@/components/unit-profile/OtherTab";
import UnitLedgerView from "@/components/unit-profile/UnitLedgerView";
import UnitTransactionHistory from "@/components/unit-profile/UnitTransactionHistory";
import UnitLedgerAccountBreakdown from "@/components/unit-profile/UnitLedgerAccountBreakdown";
import ApplyWorkflowToUnitModal from "@/components/unit-profile/ApplyWorkflowToUnitModal";
import UnitDocumentsTab from "@/components/unit-profile/UnitDocumentsTab";
import UnitTimelineTab from "@/components/unit-profile/UnitTimelineTab";
import UnitStatusTagsEditor from "@/components/units/UnitStatusTagsEditor";

export default function UnitProfilePage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { toast } = useToast();
  const [unit, setUnit] = useState<any>(null);
  const [owners, setOwners] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState(() => localStorage.getItem("unitProfileLastTab") || "ledger");
  const [workflowModalOpen, setWorkflowModalOpen] = useState(false);
  const [syncing, setSyncing] = useState(false);

  // Image URL editing state
  const [editingImage, setEditingImage] = useState(false);
  const [imageUrlInput, setImageUrlInput] = useState("");

  useEffect(() => {
    localStorage.setItem("unitProfileLastTab", activeTab);
  }, [activeTab]);

  const fetchOwners = async () => {
    if (!id) return;

    const { data, error } = await supabase
      .from("owners")
      .select("*")
      .eq("unit_id", id)
      .eq("status", "active")
      .order("is_primary", { ascending: false })
      .order("last_name", { ascending: true });

    if (error) {
      console.error("Error fetching unit owners:", error);
      setOwners([]);
      return;
    }

    setOwners(data || []);
  };

  useEffect(() => {
    if (id) {
      supabase.from("units").select("*, associations(name)").eq("id", id).single().then(({ data }) => {
        setUnit(data);
        setImageUrlInput((data as any)?.image_url || "");
        setLoading(false);
      });
      fetchOwners();
    }
  }, [id]);

  const handleSaveImageUrl = async () => {
    const trimmed = imageUrlInput.trim();
    const { error } = await supabase
      .from("units")
      .update({ image_url: trimmed || null } as any)
      .eq("id", unit.id);

    if (error) {
      toast({ variant: "destructive", title: "Error saving image URL", description: error.message });
      return;
    }

    setUnit({ ...unit, image_url: trimmed || null });
    setEditingImage(false);
    toast({ title: "Image updated" });
  };

  const handleBuildiumSync = async (direction: "pull" | "push") => {
    if (!unit?.association_id) return;
    setSyncing(true);
    try {
      const { data: sessionData } = await supabase.auth.getSession();
      const token = sessionData?.session?.access_token;
      if (!token) throw new Error("Not authenticated");

      const syncType = direction === "pull" ? "ledger" : "push_all";
      const { data, error } = await supabase.functions.invoke("buildium-sync", {
        body: { syncType, selectedAssociationIds: [unit.association_id] },
      });
      if (error) throw error;

      const results = data?.results || {};
      if (direction === "pull") {
        const l = results.ledger || {};
        toast({ title: "Buildium Pull Complete", description: `${l.imported || 0} imported, ${l.updated || 0} updated, ${l.skipped || 0} skipped` });
      } else {
        const p = results.push || {};
        toast({ title: "Buildium Push Complete", description: `${p.pushed || 0} pushed, ${p.skipped || 0} skipped, ${p.errors || 0} errors` });
      }
    } catch (err: any) {
      toast({ variant: "destructive", title: "Sync failed", description: err.message || "Unknown error" });
    } finally {
      setSyncing(false);
    }
  };

  if (loading) {
    return (
      <div className="flex min-h-[50vh] items-center justify-center">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  if (!unit) {
    return (
      <div className="text-center">
        <p className="text-muted-foreground">Unit not found.</p>
        <Button variant="link" onClick={() => navigate("/dashboard/unit-directory")}>Back to directory</Button>
      </div>
    );
  }

  const statusColor = (s: string | null) => {
    switch (s) {
      case "active": return "bg-success/20 text-success-foreground";
      case "delinquent": return "bg-destructive/10 text-destructive";
      default: return "bg-muted text-muted-foreground";
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-start gap-4">
        <Button variant="ghost" size="icon" onClick={() => navigate("/dashboard/unit-directory")}>
          <ArrowLeft className="h-5 w-5" />
        </Button>
        <div className="flex-1">
          <div className="flex items-center gap-3 flex-wrap">
            <Home className="h-6 w-6 text-primary" />
            <h1 className="text-2xl font-bold">Unit {unit.unit_number}</h1>
            <Badge variant="secondary" className={statusColor(unit.status)}>
              {unit.status ?? "active"}
            </Badge>
            <UnitStatusTagsEditor
              unitId={unit.id}
              value={unit.status_tags}
              onChange={(next) => setUnit({ ...unit, status_tags: next })}
              size="md"
            />
          </div>
          <p className="text-sm text-muted-foreground mt-1">
            {unit.associations?.name} • {unit.address || "No address"} 
            {unit.bedrooms || unit.bathrooms ? ` • ${unit.bedrooms ?? "—"} bed / ${unit.bathrooms ?? "—"} bath` : ""}
            {unit.sqft ? ` • ${unit.sqft.toLocaleString()} sq ft` : ""}
          </p>
        </div>
        <div className="flex items-center gap-2 shrink-0">
          <Button variant="outline" size="sm" className="text-xs gap-1.5" disabled={syncing} onClick={() => handleBuildiumSync("pull")}>
            <RefreshCw className={`h-3.5 w-3.5 ${syncing ? "animate-spin" : ""}`} /> Pull
          </Button>
          <Button variant="outline" size="sm" className="text-xs gap-1.5" disabled={syncing} onClick={() => handleBuildiumSync("push")}>
            <ArrowUpDown className={`h-3.5 w-3.5 ${syncing ? "animate-spin" : ""}`} /> Push
          </Button>
          <Button variant="outline" size="sm" className="text-xs gap-1.5" onClick={() => setWorkflowModalOpen(true)}>
            <Play className="h-3.5 w-3.5" /> Apply Workflow
          </Button>
        </div>
      </div>

      {/* Owners Summary */}
      <div className="rounded-lg border border-border bg-card p-4">
        <div className="flex items-center gap-2 mb-3">
          <Users className="h-4 w-4 text-primary" />
          <span className="text-sm font-semibold text-foreground">Owners</span>
          <Badge variant="secondary" className="text-xs">{owners.length}</Badge>
        </div>
        {owners.length > 0 ? (
          <div className="grid gap-2 sm:grid-cols-2">
            {owners.map((o) => (
              <Link
                key={o.id}
                to={`/dashboard/owner-roster/${o.id}`}
                className="block rounded-md border border-border bg-muted/40 px-3 py-3 transition-colors hover:bg-accent"
              >
                <div className="flex items-start justify-between gap-3">
                  <div className="min-w-0 space-y-1">
                    <div className="font-medium text-foreground break-words">
                      {`${o.first_name || ""} ${o.last_name || ""}`.trim() || "Unknown"}
                    </div>
                    {o.email && (
                      <div className="text-xs text-muted-foreground break-all">{o.email}</div>
                    )}
                    {o.phone && (
                      <div className="text-xs text-muted-foreground">{o.phone}</div>
                    )}
                  </div>
                  {o.is_primary && (
                    <Badge variant="outline" className="shrink-0 text-[10px] px-1.5 py-0">Primary</Badge>
                  )}
                </div>
              </Link>
            ))}
          </div>
        ) : (
          <p className="text-sm text-muted-foreground">No owners recorded for this unit.</p>
        )}
      </div>

      {/* Property Image with URL editor */}
      <div className="space-y-2">
        <PropertyImage address={unit.address || ""} imageUrl={unit.image_url} />
        
        {editingImage ? (
          <div className="flex items-center gap-2 max-w-md">
            <Input
              placeholder="Paste image URL…"
              value={imageUrlInput}
              onChange={(e) => setImageUrlInput(e.target.value)}
              className="text-sm"
            />
            <Button size="icon" variant="ghost" onClick={handleSaveImageUrl}>
              <Check className="h-4 w-4 text-success" />
            </Button>
            <Button size="icon" variant="ghost" onClick={() => { setEditingImage(false); setImageUrlInput(unit.image_url || ""); }}>
              <X className="h-4 w-4 text-destructive" />
            </Button>
          </div>
        ) : (
          <Button variant="ghost" size="sm" className="text-xs gap-1.5 text-muted-foreground" onClick={() => setEditingImage(true)}>
            <ImagePlus className="h-3.5 w-3.5" />
            {unit.image_url ? "Change image URL" : "Add image URL"}
          </Button>
        )}
      </div>

      {/* Tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
        <TabsList className="w-full justify-start overflow-x-auto flex-nowrap h-auto p-1">
          <TabsTrigger value="ledger" className="gap-2 whitespace-nowrap"><FileText className="h-4 w-4" /> Ledger</TabsTrigger>
          <TabsTrigger value="history" className="gap-2 whitespace-nowrap"><History className="h-4 w-4" /> Tx History</TabsTrigger>
          <TabsTrigger value="accounts" className="gap-2 whitespace-nowrap"><BarChart3 className="h-4 w-4" /> By Account</TabsTrigger>
          <TabsTrigger value="owners" className="gap-2 whitespace-nowrap"><Users className="h-4 w-4" /> Owners</TabsTrigger>
          <TabsTrigger value="tenants" className="gap-2 whitespace-nowrap"><KeyRound className="h-4 w-4" /> Tenants</TabsTrigger>
          <TabsTrigger value="violations" className="gap-2 whitespace-nowrap"><AlertTriangle className="h-4 w-4" /> Violations</TabsTrigger>
          <TabsTrigger value="arc" className="gap-2 whitespace-nowrap"><PenTool className="h-4 w-4" /> ARC Apps</TabsTrigger>
          <TabsTrigger value="updates" className="gap-2 whitespace-nowrap"><MessageSquare className="h-4 w-4" /> Updates</TabsTrigger>
          <TabsTrigger value="other" className="gap-2 whitespace-nowrap"><Settings className="h-4 w-4" /> Other</TabsTrigger>
          <TabsTrigger value="documents" className="gap-2 whitespace-nowrap"><FolderOpen className="h-4 w-4" /> Documents</TabsTrigger>
          <TabsTrigger value="timeline" className="gap-2 whitespace-nowrap"><Clock className="h-4 w-4" /> Timeline</TabsTrigger>
        </TabsList>

        <TabsContent value="ledger"><UnitLedgerView unitId={unit.id} associationId={unit.association_id} /></TabsContent>
        <TabsContent value="history"><UnitTransactionHistory unitId={unit.id} /></TabsContent>
        <TabsContent value="accounts"><UnitLedgerAccountBreakdown unitId={unit.id} /></TabsContent>
        <TabsContent value="owners"><OwnersTab unitId={unit.id} associationId={unit.association_id} onOwnersChange={fetchOwners} /></TabsContent>
        <TabsContent value="tenants"><TenantsTab unitId={unit.id} /></TabsContent>
        <TabsContent value="violations"><UnitViolationsTab unitId={unit.id} /></TabsContent>
        <TabsContent value="arc"><UnitArcApplicationsTab unitId={unit.id} /></TabsContent>
        <TabsContent value="updates"><UnitOwnerUpdatesTab unitId={unit.id} associationId={unit.association_id} /></TabsContent>
        <TabsContent value="other"><OtherTab unitId={unit.id} /></TabsContent>
        <TabsContent value="documents"><UnitDocumentsTab unitId={unit.id} associationId={unit.association_id} /></TabsContent>
        <TabsContent value="timeline"><UnitTimelineTab unitId={unit.id} associationId={unit.association_id} /></TabsContent>
      </Tabs>

      <ApplyWorkflowToUnitModal
        open={workflowModalOpen}
        onOpenChange={setWorkflowModalOpen}
        unitId={unit.id}
        unitNumber={unit.unit_number}
        associationId={unit.association_id}
        associationName={unit.associations?.name || ""}
      />
    </div>
  );
}
