"use client";

import { useState, useMemo } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Building2, CheckCircle2, Link2, Link2Off, AlertTriangle, Search } from "lucide-react";
import { Button } from "@/app/shadcn_components/ui/button";
import { Input } from "@/app/shadcn_components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogTitle,
  DialogFooter,
} from "@/app/shadcn_components/ui/dialog";

type OrgSummary = {
  id: string;
  name: string | null;
  hubspotCompanyId: string | null;
};

async function fetchCurrentOrg(portfolioId: string): Promise<OrgSummary | null> {
  const res = await fetch(`/api/portfolio/${portfolioId}/organisation`);
  if (!res.ok) throw new Error("Failed to fetch linked organisation");
  return res.json();
}

async function fetchAllOrgs(): Promise<OrgSummary[]> {
  const res = await fetch("/api/organisations");
  if (!res.ok) throw new Error("Failed to fetch organisations");
  return res.json();
}

export default function OrganisationLinkCard({ portfolioId }: { portfolioId: string }) {
  const queryClient = useQueryClient();

  const [connectOpen, setConnectOpen] = useState(false);
  const [disconnectOpen, setDisconnectOpen] = useState(false);
  const [selectedOrgId, setSelectedOrgId] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [confirmed, setConfirmed] = useState(false);

  // Current linked org
  const { data: currentOrg, isLoading: loadingCurrent } = useQuery({
    queryKey: ["portfolio-org", portfolioId],
    queryFn: () => fetchCurrentOrg(portfolioId),
  });

  // All orgs — only fetched when connect modal is open
  const { data: allOrgs = [], isLoading: loadingOrgs } = useQuery({
    queryKey: ["all-organisations"],
    queryFn: fetchAllOrgs,
    enabled: connectOpen,
  });

  const connectMutation = useMutation({
    mutationFn: async (organisationId: string) => {
      const res = await fetch(`/api/portfolio/${portfolioId}/organisation`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ organisationId }),
      });
      if (!res.ok) throw new Error("Failed to connect organisation");
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["portfolio-org", portfolioId] });
      setConnectOpen(false);
      setSelectedOrgId(null);
      setConfirmed(false);
      setSearchQuery("");
    },
  });

  const disconnectMutation = useMutation({
    mutationFn: async () => {
      const res = await fetch(`/api/portfolio/${portfolioId}/organisation`, {
        method: "DELETE",
      });
      if (!res.ok) throw new Error("Failed to disconnect organisation");
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["portfolio-org", portfolioId] });
      setDisconnectOpen(false);
    },
  });

  const filteredOrgs = useMemo(
    () =>
      allOrgs.filter((o) =>
        (o.name ?? "").toLowerCase().includes(searchQuery.toLowerCase()),
      ),
    [allOrgs, searchQuery],
  );

  const selectedOrg = allOrgs.find((o) => o.id === selectedOrgId) ?? null;

  return (
    <div className="rounded-xl border border-brandblue/15 bg-white shadow-sm mt-4 overflow-hidden">
      {/* Header */}
      <div className="flex items-center gap-3 px-5 py-4 border-b border-gray-100 bg-brandlightblue/20">
        <div className="p-2 rounded-lg bg-brandblue/10">
          <Building2 className="h-4 w-4 text-brandblue" />
        </div>
        <div>
          <p className="text-sm font-semibold text-brandblue">Organisation Link</p>
          <p className="text-xs text-gray-500 mt-0.5">
            Connect this portfolio to an organisation to enable live project tracking
          </p>
        </div>
      </div>

      {/* Body */}
      <div className="px-5 py-4">
        {loadingCurrent ? (
          <div className="h-10 bg-gray-100 rounded-lg animate-pulse w-48" />
        ) : currentOrg ? (
          <div className="flex items-center justify-between gap-4">
            <div className="flex items-center gap-3">
              <CheckCircle2 className="h-5 w-5 text-emerald-500 shrink-0" />
              <div>
                <p className="text-sm font-semibold text-gray-800">{currentOrg.name ?? "Unnamed organisation"}</p>
                <p className="text-xs text-gray-400 mt-0.5">
                  Connected · HubSpot ID: {currentOrg.hubspotCompanyId ?? "—"}
                </p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Button
                size="sm"
                variant="outline"
                className="h-8 text-xs border-brandblue/20 text-brandblue hover:bg-brandlightblue/30"
                onClick={() => {
                  setConnectOpen(true);
                  setSelectedOrgId(null);
                  setConfirmed(false);
                  setSearchQuery("");
                }}
              >
                <Link2 className="h-3.5 w-3.5 mr-1.5" />
                Change
              </Button>
              <Button
                size="sm"
                variant="outline"
                className="h-8 text-xs border-red-200 text-red-600 hover:bg-red-50"
                onClick={() => setDisconnectOpen(true)}
              >
                <Link2Off className="h-3.5 w-3.5 mr-1.5" />
                Disconnect
              </Button>
            </div>
          </div>
        ) : (
          <div className="flex items-center justify-between gap-4">
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center">
                <Building2 className="h-4 w-4 text-gray-400" />
              </div>
              <p className="text-sm text-gray-500">No organisation linked</p>
            </div>
            <Button
              size="sm"
              className="h-8 text-xs bg-brandblue hover:bg-brandmidblue"
              onClick={() => {
                setConnectOpen(true);
                setSelectedOrgId(null);
                setConfirmed(false);
                setSearchQuery("");
              }}
            >
              <Link2 className="h-3.5 w-3.5 mr-1.5" />
              Connect Organisation
            </Button>
          </div>
        )}
      </div>

      {/* ── Connect modal ─────────────────────────────────────────────── */}
      <Dialog open={connectOpen} onOpenChange={(v) => { setConnectOpen(v); if (!v) { setSelectedOrgId(null); setConfirmed(false); setSearchQuery(""); } }}>
        <DialogContent className="max-w-md">
          <DialogTitle className="text-brandblue">Connect Organisation</DialogTitle>

          {/* Search */}
          <div className="relative mt-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
            <Input
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search organisations…"
              className="pl-9 h-9 text-sm border-gray-200"
            />
          </div>

          {/* Org list */}
          <div className="mt-2 max-h-56 overflow-y-auto rounded-lg border border-gray-200 divide-y divide-gray-100">
            {loadingOrgs ? (
              <div className="p-4 text-sm text-gray-400 text-center">Loading…</div>
            ) : filteredOrgs.length === 0 ? (
              <div className="p-4 text-sm text-gray-400 text-center">No organisations found</div>
            ) : (
              filteredOrgs.map((org) => (
                <button
                  key={org.id}
                  onClick={() => setSelectedOrgId(org.id)}
                  className={`w-full text-left px-4 py-2.5 transition-colors text-sm ${
                    selectedOrgId === org.id
                      ? "bg-brandlightblue/50 text-brandblue font-medium"
                      : "hover:bg-gray-50 text-gray-700"
                  }`}
                >
                  <span className="block font-medium">{org.name ?? "Unnamed"}</span>
                  {org.hubspotCompanyId && (
                    <span className="text-xs text-gray-400">HubSpot ID: {org.hubspotCompanyId}</span>
                  )}
                </button>
              ))
            )}
          </div>

          {/* Warning */}
          <div className="flex items-start gap-2.5 p-3 rounded-lg bg-amber-50 border border-amber-200 mt-1">
            <AlertTriangle className="h-4 w-4 text-amber-500 mt-0.5 shrink-0" />
            <p className="text-xs text-amber-700 leading-relaxed">
              Viewers of this portfolio will be able to see <strong>live project tracking data</strong> associated with the selected organisation.
            </p>
          </div>

          {/* Confirmation checkbox */}
          <label className="flex items-center gap-2.5 cursor-pointer select-none mt-1">
            <input
              type="checkbox"
              checked={confirmed}
              onChange={(e) => setConfirmed(e.target.checked)}
              className="h-4 w-4 rounded border-gray-300 text-brandblue accent-brandblue"
            />
            <span className="text-sm text-gray-700">I understand and want to connect this organisation</span>
          </label>

          <DialogFooter className="mt-2">
            <Button variant="outline" onClick={() => setConnectOpen(false)} className="text-sm">
              Cancel
            </Button>
            <Button
              onClick={() => selectedOrgId && connectMutation.mutate(selectedOrgId)}
              disabled={!selectedOrgId || !confirmed || connectMutation.isPending}
              className="bg-brandblue hover:bg-brandmidblue text-sm"
            >
              {connectMutation.isPending ? "Connecting…" : `Connect${selectedOrg ? ` "${selectedOrg.name}"` : ""}`}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* ── Disconnect confirm dialog ──────────────────────────────────── */}
      <Dialog open={disconnectOpen} onOpenChange={setDisconnectOpen}>
        <DialogContent className="max-w-sm">
          <DialogTitle className="text-gray-800">Disconnect organisation?</DialogTitle>
          <p className="text-sm text-gray-600 leading-relaxed">
            Are you sure you want to disconnect{" "}
            <strong>{currentOrg?.name ?? "this organisation"}</strong>?
            Live project tracking data will no longer be visible to portfolio viewers.
          </p>
          <DialogFooter className="mt-2">
            <Button variant="outline" onClick={() => setDisconnectOpen(false)} className="text-sm">
              Cancel
            </Button>
            <Button
              onClick={() => disconnectMutation.mutate()}
              disabled={disconnectMutation.isPending}
              className="bg-red-600 hover:bg-red-700 text-white text-sm"
            >
              {disconnectMutation.isPending ? "Disconnecting…" : "Disconnect"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
