import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { format } from "date-fns";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { Calendar } from "@/components/ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useToast } from "@/hooks/use-toast";
import { invokeEdgeFunction } from "@/lib/edgeFunctionUtils";
import { supabase } from "@/integrations/supabase/client";
import {
  CheckCircle2, XCircle, Loader2, RefreshCw, Building2, Users, BookOpen, DollarSign, Home, Trash2, AlertTriangle, Upload, CalendarIcon, Clock, RotateCcw, Eye,
} from "lucide-react";
import { cn } from "@/lib/utils";
import BuildiumGLMappingCard from "@/components/settings/BuildiumGLMappingCard";
import BuildiumUnitMappingCard from "@/components/settings/BuildiumUnitMappingCard";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
} from "@/components/ui/alert-dialog";

type SyncType = "associations" | "units" | "owners" | "financials" | "ledger" | "push_charges" | "push_payments" | "push_all" | "reset_ledgers" | "all";
type DeleteType = "charges" | "payments" | "owners" | "units" | "financials" | "all";

interface SyncResults {
  associations?: { fetched: number; upserted: number; excluded?: number };
  units?: { fetched: number; created: number; linked: number; skipped: number };
  owners?: { fetched: number; imported: number; skipped: number };
  financials?: { fetched: number; upserted: number };
  ledger?: { fetched: number; imported: number; skipped: number; updated?: number };
  push?: { pushed: number; skipped: number; errors: number; skipSamples?: any[]; errorSamples?: any[] };
  reset?: { deleted: number };
}

interface Association {
  id: string;
  name: string;
  status: string;
}

export default function BuildiumSettingsPage() {
  const { toast } = useToast();
  const navigate = useNavigate();
  const [staging, setStaging] = useState(false);
  const [pendingBatchCount, setPendingBatchCount] = useState<number>(0);
  const [testing, setTesting] = useState(false);
  const [connected, setConnected] = useState<boolean | null>(null);
  const [syncing, setSyncing] = useState<SyncType | null>(null);
  const [results, setResults] = useState<SyncResults | null>(null);
  const [associations, setAssociations] = useState<Association[]>([]);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [loadingAssociations, setLoadingAssociations] = useState(true);
  const [deleteConfirm, setDeleteConfirm] = useState<DeleteType | null>(null);
  const [deleting, setDeleting] = useState<DeleteType | null>(null);
  const [dateFrom, setDateFrom] = useState<Date | undefined>(undefined);
  const [dateTo, setDateTo] = useState<Date | undefined>(undefined);
  const [lastSyncDates, setLastSyncDates] = useState<Record<string, string>>({});

  useEffect(() => {
    const fetchAssociations = async () => {
      const { data } = await supabase
        .from("associations")
        .select("id, name, status")
        .eq("status", "active")
        .order("name");
      setAssociations(data || []);
      setSelectedIds((data || []).map((a) => a.id));
      setLoadingAssociations(false);
    };
    fetchAssociations();
    const fetchLastSyncDates = async () => {
      const { data } = await supabase
        .from("company_settings")
        .select("key, value")
        .like("key", "buildium_last_sync_%");
      const map: Record<string, string> = {};
      for (const row of data || []) {
        const syncType = row.key.replace("buildium_last_sync_", "");
        if (row.value) map[syncType] = row.value;
      }
      setLastSyncDates(map);
    };
    fetchLastSyncDates();
    const fetchPendingCount = async () => {
      const { count } = await supabase
        .from("buildium_import_staging")
        .select("id", { count: "exact", head: true })
        .eq("status", "pending");
      setPendingBatchCount(count || 0);
    };
    fetchPendingCount();
  }, []);

  const stageForReview = async (kindsOverride?: string[], label?: string) => {
    if (selectedIds.length === 0) {
      toast({ variant: "destructive", title: "No associations selected" });
      return;
    }
    setStaging(true);
    try {
      const { data, error } = await invokeEdgeFunction("buildium-import-stage", {
        body: {
          kinds: kindsOverride || ["unit", "owner", "gl_account", "ledger_entry"],
          selectedAssociationIds: selectedIds,
          dateFrom: dateFrom ? format(dateFrom, "yyyy-MM-dd") : undefined,
          dateTo: dateTo ? format(dateTo, "yyyy-MM-dd") : undefined,
        },
      });
      if (error) throw error;
      toast({
        title: label ? `${label} pulled for review` : "Pulled for review",
        description: `${data.inserted} items staged. Review them before applying.`,
      });
      navigate(`/dashboard/settings/buildium/review?batch_id=${data.batch_id}`);
    } catch (err: any) {
      toast({ variant: "destructive", title: "Pull failed", description: err?.message || String(err) });
    } finally {
      setStaging(false);
    }
  };

  const toggleAssociation = (id: string) => {
    setSelectedIds((prev) =>
      prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
    );
  };

  const toggleAll = () => {
    if (selectedIds.length === associations.length) {
      setSelectedIds([]);
    } else {
      setSelectedIds(associations.map((a) => a.id));
    }
  };

  const testConnection = async () => {
    setTesting(true);
    setConnected(null);
    try {
      const { data, error } = await invokeEdgeFunction("buildium-sync", {
        body: { syncType: "associations", selectedAssociationIds: [] },
      });
      if (error) throw error;
      setConnected(true);
      toast({ title: "Connected to Buildium successfully" });
    } catch {
      setConnected(false);
      toast({ variant: "destructive", title: "Connection failed", description: "Check your Buildium API credentials." });
    } finally {
      setTesting(false);
    }
  };

  const runSync = async (type: SyncType) => {
    if (selectedIds.length === 0 && type !== "associations") {
      toast({ variant: "destructive", title: "No associations selected", description: "Select at least one association to sync." });
      return;
    }

    setSyncing(type);
    setResults(null);
    try {
      const { data, error } = await invokeEdgeFunction("buildium-sync", {
        body: {
          syncType: type,
          selectedAssociationIds: selectedIds,
          ...(type === "ledger" || type === "all" ? {
            dateFrom: dateFrom ? format(dateFrom, "yyyy-MM-dd") : undefined,
            dateTo: dateTo ? format(dateTo, "yyyy-MM-dd") : undefined,
          } : {}),
        },
      });
      if (error) throw error;
      setResults(data.results);
      setConnected(true);
      // Update last sync dates
      setLastSyncDates(prev => ({ ...prev, [type]: new Date().toISOString() }));
      const pushResult = data.results?.push;
      if (pushResult?.errors > 0) {
        toast({ variant: "destructive", title: "Push completed with errors", description: `${pushResult.pushed} pushed, ${pushResult.errors} failed. See Sync Results below.` });
      } else {
        toast({ title: type === "reset_ledgers" ? "Ledgers cleared successfully" : "Sync completed successfully" });
      }
    } catch (err: any) {
      toast({ variant: "destructive", title: "Sync failed", description: err.message });
    } finally {
      setSyncing(null);
    }
  };

  const deleteImportedData = async (type: DeleteType) => {
    if (selectedIds.length === 0) {
      toast({ variant: "destructive", title: "No associations selected" });
      return;
    }
    setDeleting(type);
    setDeleteConfirm(null);
    try {
      const deleteTypes = type === "all" ? ["charges", "payments", "financials", "owners", "units"] : [type];
      let totalDeleted = 0;

      for (const dt of deleteTypes) {
        let table = "";
        let filter: { column: string; value: any } | null = null;

        switch (dt) {
          case "charges":
          case "payments":
            // Delete Buildium-imported ledger entries for selected associations
            for (const assocId of selectedIds) {
              const { count } = await supabase
                .from("owner_ledger_entries")
                .delete({ count: "exact" })
                .eq("association_id", assocId)
                .eq("reference_type", "buildium");
              totalDeleted += count || 0;
            }
            continue;
          case "owners":
            for (const assocId of selectedIds) {
              const { count } = await supabase
                .from("owners")
                .delete({ count: "exact" })
                .eq("association_id", assocId)
                .not("buildium_owner_id", "is", null);
              totalDeleted += count || 0;
            }
            continue;
          case "units":
            for (const assocId of selectedIds) {
              const { count } = await supabase
                .from("units")
                .delete({ count: "exact" })
                .eq("association_id", assocId)
                .not("buildium_unit_id", "is", null);
              totalDeleted += count || 0;
            }
            continue;
          case "financials":
            for (const assocId of selectedIds) {
              const { count } = await supabase
                .from("chart_of_accounts")
                .delete({ count: "exact" })
                .eq("association_id", assocId);
              totalDeleted += count || 0;
            }
            continue;
        }
      }

      toast({ title: "Deleted successfully", description: `${totalDeleted} records removed.` });
    } catch (err: any) {
      toast({ variant: "destructive", title: "Delete failed", description: err.message });
    } finally {
      setDeleting(null);
    }
  };

  const deleteLabels: Record<DeleteType, string> = {
    charges: "Buildium ledger entries (charges & payments)",
    payments: "Buildium ledger entries (charges & payments)",
    owners: "Buildium-imported owners",
    units: "Buildium-imported units",
    financials: "GL accounts",
    all: "ALL Buildium-imported data (ledger, owners, units, GL)",
  };

  const formatLastSync = (type: string) => {
    const ts = lastSyncDates[type];
    if (!ts) return null;
    try {
      return format(new Date(ts), "MMM d, yyyy h:mm a");
    } catch {
      return null;
    }
  };

  const syncCards: { type: SyncType; title: string; desc: string; icon: any; deleteType?: DeleteType; direction?: "pull" | "push" }[] = [
    { type: "associations", title: "Associations", desc: "Import communities, addresses, and contact info", icon: Building2 },
    { type: "units", title: "Units", desc: "Import units from Buildium ownership accounts", icon: Home, deleteType: "units" },
    { type: "owners", title: "Owners", desc: "Import property owners, emails, and phone numbers", icon: Users, deleteType: "owners" },
    { type: "financials", title: "GL Accounts", desc: "Import chart of accounts and GL structure", icon: BookOpen, deleteType: "financials" },
    { type: "ledger", title: "Pull Payments", desc: "Pull payments from Buildium into unit ledgers (charges are not pulled)", icon: DollarSign, deleteType: "charges" },
  ];

  const pushCards: { type: SyncType; title: string; desc: string; icon: any }[] = [
    { type: "push_charges", title: "Push Charges", desc: "Send locally created charges to Buildium (payments are not pushed)", icon: Upload },
  ];

  return (
    <div className="space-y-6 max-w-3xl">
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2">
            <Building2 className="h-6 w-6 text-primary" />
            Buildium Integration
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            Sync associations, owners, and financial data with Buildium in both directions.
          </p>
        </div>
      </div>

      {/* Connection Status */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Connection Status</CardTitle>
          <CardDescription>Test your Buildium API credentials before syncing.</CardDescription>
        </CardHeader>
        <CardContent className="flex items-center gap-4">
          <Button onClick={testConnection} disabled={testing} variant="outline" className="gap-2">
            {testing ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
            Test Connection
          </Button>
          {connected === true && (
            <Badge variant="outline" className="text-emerald-600 border-emerald-200 bg-emerald-50 gap-1">
              <CheckCircle2 className="h-3 w-3" /> Connected
            </Badge>
          )}
          {connected === false && (
            <Badge variant="outline" className="text-destructive border-destructive/30 bg-destructive/10 gap-1">
              <XCircle className="h-3 w-3" /> Failed
            </Badge>
          )}
        </CardContent>
      </Card>

      {/* Association Selector */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Select Associations to Sync</CardTitle>
          <CardDescription>Choose which associations should be included when syncing data. Archived associations won't reappear.</CardDescription>
        </CardHeader>
        <CardContent>
          {loadingAssociations ? (
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin" /> Loading associations...
            </div>
          ) : associations.length === 0 ? (
            <p className="text-sm text-muted-foreground">No active associations found. Sync associations first.</p>
          ) : (
            <div className="space-y-3">
              <div className="flex items-center gap-2 pb-2 border-b">
                <Checkbox
                  checked={selectedIds.length === associations.length}
                  onCheckedChange={toggleAll}
                  id="select-all"
                />
                <label htmlFor="select-all" className="text-sm font-medium cursor-pointer">
                  Select All ({selectedIds.length}/{associations.length})
                </label>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-60 overflow-y-auto">
                {associations.map((assoc) => (
                  <div key={assoc.id} className="flex items-center gap-2">
                    <Checkbox
                      checked={selectedIds.includes(assoc.id)}
                      onCheckedChange={() => toggleAssociation(assoc.id)}
                      id={`assoc-${assoc.id}`}
                    />
                    <label htmlFor={`assoc-${assoc.id}`} className="text-sm cursor-pointer truncate">
                      {assoc.name}
                    </label>
                  </div>
                ))}
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* GL Mapping Tabs */}
      <Tabs defaultValue="association" className="w-full">
        <TabsList>
          <TabsTrigger value="association">Association Mapping</TabsTrigger>
          <TabsTrigger value="unit">Unit Mapping</TabsTrigger>
        </TabsList>
        <TabsContent value="association">
          <BuildiumGLMappingCard associations={associations} />
        </TabsContent>
        <TabsContent value="unit">
          <BuildiumUnitMappingCard associations={associations} />
        </TabsContent>
      </Tabs>

      {/* Sync Cards */}
      {/* Date Range Filter for Ledger Sync */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <CalendarIcon className="h-5 w-5 text-primary" />
            Transaction Date Filter
          </CardTitle>
          <CardDescription>
            Optionally limit which Buildium transactions to import by date range. Leave blank to import all.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex flex-wrap items-end gap-4">
            <div className="space-y-1.5">
              <label className="text-sm font-medium">From</label>
              <Popover>
                <PopoverTrigger asChild>
                  <Button variant="outline" className={cn("w-[180px] justify-start text-left font-normal", !dateFrom && "text-muted-foreground")}>
                    <CalendarIcon className="mr-2 h-4 w-4" />
                    {dateFrom ? format(dateFrom, "MMM d, yyyy") : "Start date"}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0" align="start">
                  <Calendar mode="single" selected={dateFrom} onSelect={setDateFrom} initialFocus className={cn("p-3 pointer-events-auto")} />
                </PopoverContent>
              </Popover>
            </div>
            <div className="space-y-1.5">
              <label className="text-sm font-medium">To</label>
              <Popover>
                <PopoverTrigger asChild>
                  <Button variant="outline" className={cn("w-[180px] justify-start text-left font-normal", !dateTo && "text-muted-foreground")}>
                    <CalendarIcon className="mr-2 h-4 w-4" />
                    {dateTo ? format(dateTo, "MMM d, yyyy") : "End date"}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0" align="start">
                  <Calendar mode="single" selected={dateTo} onSelect={setDateTo} initialFocus className={cn("p-3 pointer-events-auto")} />
                </PopoverContent>
              </Popover>
            </div>
            {(dateFrom || dateTo) && (
              <Button variant="ghost" size="sm" onClick={() => { setDateFrom(undefined); setDateTo(undefined); }}>
                Clear dates
              </Button>
            )}
          </div>
          {(dateFrom || dateTo) && (
            <p className="text-xs text-muted-foreground mt-2">
              Only transactions {dateFrom ? `from ${format(dateFrom, "MMM d, yyyy")}` : ""}{dateFrom && dateTo ? " " : ""}{dateTo ? `through ${format(dateTo, "MMM d, yyyy")}` : ""} will be imported during ledger sync.
            </p>
          )}
        </CardContent>
      </Card>

      {/* Pull for Review (staged imports) */}
      <Card className="border-primary/30 bg-primary/5">
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <Eye className="h-5 w-5 text-primary" /> Pull for Review
          </CardTitle>
          <CardDescription>
            Fetch units, owners, GL accounts, and ledger entries from Buildium and stage them for row-by-row review before they're applied to the live system.
          </CardDescription>
        </CardHeader>
        <CardContent className="flex flex-wrap items-center gap-3">
          <Button onClick={() => stageForReview()} disabled={staging || syncing !== null} className="gap-2">
            {staging ? <Loader2 className="h-4 w-4 animate-spin" /> : <Eye className="h-4 w-4" />}
            {staging ? "Pulling..." : "Pull from Buildium for Review"}
          </Button>
          <Button
            variant="outline"
            onClick={() => stageForReview(["arc_application"], "ARC Applications")}
            disabled={staging || syncing !== null}
            className="gap-2"
          >
            {staging ? <Loader2 className="h-4 w-4 animate-spin" /> : <Eye className="h-4 w-4" />}
            Pull ARC Applications
          </Button>
          <Button variant="outline" onClick={() => navigate("/dashboard/settings/buildium/review")} className="gap-2">
            Open Review Queue
            {pendingBatchCount > 0 && (
              <Badge variant="secondary">{pendingBatchCount} pending</Badge>
            )}
          </Button>
        </CardContent>
      </Card>

      <div className="grid gap-4">
        <p className="text-xs text-muted-foreground -mb-2">
          Direct Sync writes to the live system immediately (no review). Use “Pull for Review” above to inspect changes first.
        </p>
        {syncCards.map(({ type, title, desc, icon: Icon, deleteType }) => (
          <Card key={type}>
            <CardContent className="flex items-center justify-between py-5 flex-wrap gap-3">
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
                  <Icon className="h-5 w-5 text-primary" />
                </div>
                <div>
                  <p className="font-medium">{title}</p>
                  <p className="text-sm text-muted-foreground">{desc}</p>
                  {formatLastSync(type) && (
                    <p className="text-xs text-muted-foreground flex items-center gap-1 mt-0.5">
                      <Clock className="h-3 w-3" /> Last synced: {formatLastSync(type)}
                    </p>
                  )}
                </div>
              </div>
              <div className="flex items-center gap-2">
                {deleteType && (
                  <Button
                    onClick={() => setDeleteConfirm(deleteType)}
                    disabled={syncing !== null || deleting !== null}
                    variant="ghost"
                    size="icon"
                    className="text-destructive hover:text-destructive hover:bg-destructive/10"
                    title={`Delete imported ${title.toLowerCase()}`}
                  >
                    {deleting === deleteType ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
                  </Button>
                )}
                <Button
                  onClick={() => runSync(type)}
                  disabled={syncing !== null || deleting !== null}
                  variant="outline"
                  className="gap-2"
                >
                  {syncing === type ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
                  {syncing === type ? "Syncing..." : "Sync"}
                </Button>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Push to Buildium */}
      <div>
        <h2 className="text-lg font-semibold mb-3 flex items-center gap-2">
          <Upload className="h-5 w-5 text-primary" /> Push to Buildium
        </h2>
            <p className="text-sm text-muted-foreground mb-4">Send locally created charges to Buildium. Payments are only pulled from Buildium.</p>
        <div className="grid gap-4">
          {pushCards.map(({ type, title, desc, icon: Icon }) => (
            <Card key={type}>
              <CardContent className="flex items-center justify-between py-5">
                <div className="flex items-center gap-3">
                  <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
                    <Icon className="h-5 w-5 text-primary" />
                  </div>
                  <div>
                    <p className="font-medium">{title}</p>
                    <p className="text-sm text-muted-foreground">{desc}</p>
                    {formatLastSync(type) && (
                      <p className="text-xs text-muted-foreground flex items-center gap-1 mt-0.5">
                        <Clock className="h-3 w-3" /> Last pushed: {formatLastSync(type)}
                      </p>
                    )}
                  </div>
                </div>
                <Button
                  onClick={() => runSync(type)}
                  disabled={syncing !== null || deleting !== null}
                  variant="outline"
                  className="gap-2"
                >
                  {syncing === type ? <Loader2 className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}
                  {syncing === type ? "Pushing..." : "Push"}
                </Button>
              </CardContent>
            </Card>
          ))}
          <Card>
            <CardContent className="flex items-center justify-between py-5">
              <div>
                <p className="font-medium">Push All</p>
                <p className="text-sm text-muted-foreground">Push all local charges to Buildium at once.</p>
              </div>
              <Button onClick={() => runSync("push_all")} disabled={syncing !== null || deleting !== null} className="gap-2">
                {syncing === "push_all" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}
                {syncing === "push_all" ? "Pushing..." : "Push All"}
              </Button>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Sync All / Delete All */}
      <Card className="border-destructive/30">
        <CardContent className="flex items-center justify-between py-5 flex-wrap gap-3">
          <div className="space-y-1">
            <p className="font-medium flex items-center gap-2">
              <RotateCcw className="h-4 w-4 text-destructive" /> Reset Ledgers for Resync
            </p>
            <p className="text-sm text-muted-foreground">Clears ledger entries and recalculates from Buildium on the next ledger sync. Owner, collection, delinquency, and legal statuses are preserved.</p>
          </div>
          <Button
            onClick={() => runSync("reset_ledgers")}
            disabled={syncing !== null || deleting !== null}
            variant="outline"
            className="gap-2 text-destructive border-destructive/30 hover:bg-destructive/10 hover:text-destructive"
          >
            {syncing === "reset_ledgers" ? <Loader2 className="h-4 w-4 animate-spin" /> : <RotateCcw className="h-4 w-4" />}
            {syncing === "reset_ledgers" ? "Clearing..." : "Clear Ledgers"}
          </Button>
        </CardContent>
      </Card>

      {/* Sync All / Delete All */}
      <Card>
        <CardContent className="flex items-center justify-between py-5">
          <div>
            <p className="font-medium">Full Sync</p>
            <p className="text-sm text-muted-foreground">Pull all selected associations, owners, and GL accounts at once.</p>
          </div>
          <div className="flex items-center gap-2">
            <Button
              onClick={() => setDeleteConfirm("all")}
              disabled={syncing !== null || deleting !== null}
              variant="outline"
              className="gap-2 text-destructive border-destructive/30 hover:bg-destructive/10 hover:text-destructive"
            >
              {deleting === "all" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
              Delete All
            </Button>
            <Button onClick={() => runSync("all")} disabled={syncing !== null || deleting !== null} className="gap-2">
              {syncing === "all" ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
              {syncing === "all" ? "Syncing..." : "Sync All"}
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Results */}
      {results && (
        <Card className="border-emerald-200 bg-emerald-50/50">
          <CardHeader>
            <CardTitle className="text-lg text-emerald-800 flex items-center gap-2">
              <CheckCircle2 className="h-5 w-5" /> Sync Results
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              {results.associations && (
                <div className="bg-background p-4 rounded-lg border text-center">
                  <div className="text-2xl font-bold">{results.associations.upserted}</div>
                  <div className="text-xs text-muted-foreground mt-1">Associations Synced</div>
                  {(results.associations.excluded ?? 0) > 0 && (
                    <div className="text-[10px] text-amber-500 mt-1">{results.associations.excluded} excluded</div>
                  )}
                </div>
              )}
              {results.units && (
                <div className="bg-background p-4 rounded-lg border text-center">
                  <div className="text-2xl font-bold text-blue-600">{results.units.created}</div>
                  <div className="text-xs text-muted-foreground mt-1">Units Created</div>
                  <div className="text-[10px] text-muted-foreground">{results.units.linked} linked</div>
                  {results.units.skipped > 0 && (
                    <div className="text-[10px] text-amber-500 mt-1">{results.units.skipped} skipped</div>
                  )}
                </div>
              )}
              {results.owners && (
                <div className="bg-background p-4 rounded-lg border text-center">
                  <div className="text-2xl font-bold text-emerald-600">{results.owners.imported}</div>
                  <div className="text-xs text-muted-foreground mt-1">Owners Imported</div>
                  {results.owners.skipped > 0 && (
                    <div className="text-[10px] text-amber-500 mt-1">{results.owners.skipped} skipped</div>
                  )}
                </div>
              )}
              {results.financials && (
                <div className="bg-background p-4 rounded-lg border text-center">
                  <div className="text-2xl font-bold">{results.financials.upserted}</div>
                  <div className="text-xs text-muted-foreground mt-1">GL Accounts Synced</div>
                </div>
              )}
              {results.ledger && (
                <div className="bg-background p-4 rounded-lg border text-center">
                  <div className="text-2xl font-bold text-amber-600">{results.ledger.imported}</div>
                  <div className="text-xs text-muted-foreground mt-1">Ledger Entries Imported</div>
                  {(results.ledger.updated ?? 0) > 0 && (
                    <div className="text-[10px] text-blue-500 mt-1">{results.ledger.updated} updated</div>
                  )}
                  {results.ledger.skipped > 0 && (
                    <div className="text-[10px] text-amber-500 mt-1">{results.ledger.skipped} skipped</div>
                  )}
                </div>
              )}
              {results.push && (
                <div className="bg-background p-4 rounded-lg border col-span-full">
                  <div className="flex flex-wrap gap-6 justify-center text-center">
                    <div>
                      <div className="text-2xl font-bold text-primary">{results.push.pushed}</div>
                      <div className="text-xs text-muted-foreground mt-1">Pushed to Buildium</div>
                    </div>
                    {results.push.skipped > 0 && (
                      <div>
                        <div className="text-2xl font-bold text-amber-500">{results.push.skipped}</div>
                        <div className="text-xs text-muted-foreground mt-1">Skipped</div>
                      </div>
                    )}
                    {results.push.errors > 0 && (
                      <div>
                        <div className="text-2xl font-bold text-destructive">{results.push.errors}</div>
                        <div className="text-xs text-muted-foreground mt-1">Errors</div>
                      </div>
                    )}
                  </div>
                  {Array.isArray(results.push.skipSamples) && results.push.skipSamples.length > 0 && (
                    <div className="mt-4">
                      <div className="text-xs font-semibold text-amber-600 mb-1">Skip reasons (sample):</div>
                      <pre className="text-[10px] bg-muted p-2 rounded max-h-48 overflow-auto whitespace-pre-wrap">
                        {JSON.stringify(results.push.skipSamples, null, 2)}
                      </pre>
                    </div>
                  )}
                  {Array.isArray(results.push.errorSamples) && results.push.errorSamples.length > 0 && (
                    <div className="mt-4">
                      <div className="text-xs font-semibold text-destructive mb-1">Buildium errors (sample):</div>
                      <pre className="text-[10px] bg-muted p-2 rounded max-h-48 overflow-auto whitespace-pre-wrap">
                        {JSON.stringify(results.push.errorSamples, null, 2)}
                      </pre>
                    </div>
                  )}
                </div>
              )}
              {results.reset && (
                <div className="bg-background p-4 rounded-lg border text-center">
                  <div className="text-2xl font-bold text-destructive">{results.reset.deleted}</div>
                  <div className="text-xs text-muted-foreground mt-1">Ledger Entries Cleared</div>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={deleteConfirm !== null} onOpenChange={() => setDeleteConfirm(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <AlertTriangle className="h-5 w-5 text-destructive" />
              Delete Imported Data
            </AlertDialogTitle>
            <AlertDialogDescription>
              This will permanently delete <strong>{deleteConfirm ? deleteLabels[deleteConfirm] : ""}</strong> for the {selectedIds.length} selected association(s). This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              onClick={() => deleteConfirm && deleteImportedData(deleteConfirm)}
            >
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}