import { useEffect, useMemo, useState } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { useSetAtom } from "jotai";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
  RefreshCw,
  Trash2,
  Globe,
  ArrowRight,
  ExternalLink,
} from "lucide-react";
import { ipc } from "@/ipc/types";
import type { Connector } from "@/ipc/types";
import { selectedConnectorIdAtom } from "@/atoms/appAtoms";
import { useLoadConnectors } from "@/hooks/useLoadConnectors";
import { useLoadConnector } from "@/hooks/useLoadConnector";
import { queryKeys } from "@/lib/queryKeys";
import { showError, showSuccess } from "@/lib/toast";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";

export default function ConnectorsPage() {
  const { t } = useTranslation("home");
  const navigate = useNavigate();
  const search = useSearch({ from: "/connectors" });
  const queryClient = useQueryClient();
  const setSelectedConnectorId = useSetAtom(selectedConnectorIdAtom);
  const connectorId = search.id ?? null;
  const { connectors } = useLoadConnectors();
  const { connector, loading } = useLoadConnector(connectorId);

  const [url, setUrl] = useState("");
  const [name, setName] = useState("");

  useEffect(() => {
    setSelectedConnectorId(connectorId);
  }, [connectorId, setSelectedConnectorId]);

  const importMutation = useMutation({
    mutationFn: (params: { url: string; name?: string }) =>
      ipc.connector.importOpenApiConnector(params),
    onSuccess: async (created: Connector) => {
      await queryClient.invalidateQueries({
        queryKey: queryKeys.connectors.all,
      });
      await queryClient.invalidateQueries({
        queryKey: queryKeys.connectors.detail({ connectorId: created.id }),
      });
      navigate({ to: "/connectors", search: { id: created.id } });
      setUrl("");
      setName("");
      showSuccess(t("connectors.messages.imported"));
    },
    onError: (error) => showError(error),
  });

  const refreshMutation = useMutation({
    mutationFn: (id: number) =>
      ipc.connector.refreshConnector({ connectorId: id }),
    onSuccess: async (updated: Connector) => {
      await queryClient.invalidateQueries({
        queryKey: queryKeys.connectors.all,
      });
      await queryClient.invalidateQueries({
        queryKey: queryKeys.connectors.detail({ connectorId: updated.id }),
      });
      showSuccess(t("connectors.messages.refreshed"));
    },
    onError: (error) => showError(error),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: number) =>
      ipc.connector.deleteConnector({ connectorId: id }),
    onSuccess: async () => {
      await queryClient.invalidateQueries({
        queryKey: queryKeys.connectors.all,
      });
      if (connectorId) {
        await queryClient.removeQueries({
          queryKey: queryKeys.connectors.detail({ connectorId }),
        });
      }
      navigate({ to: "/connectors", search: {} });
      showSuccess(t("connectors.messages.deleted"));
    },
    onError: (error) => showError(error),
  });

  const groupedEndpoints = useMemo(() => {
    if (!connector) return [];

    const groups = new Map<string, typeof connector.endpoints>();
    for (const endpoint of connector.endpoints) {
      const key = endpoint.tags[0] || t("connectors.untagged");
      const existing = groups.get(key) ?? [];
      existing.push(endpoint);
      groups.set(key, existing);
    }
    return Array.from(groups.entries());
  }, [connector, t]);

  useEffect(() => {
    if (!connectorId && connectors.length > 0) {
      setSelectedConnectorId(null);
    }
  }, [connectorId, connectors.length, setSelectedConnectorId]);

  return (
    <div className="min-h-screen w-full px-8 py-6">
      <div className="max-w-6xl mx-auto space-y-6">
        <header className="space-y-2">
          <div className="flex items-center gap-2 text-muted-foreground">
            <Globe className="h-4 w-4" />
            <span className="text-sm">{t("connectors.kicker")}</span>
          </div>
          <h1 className="text-3xl font-bold">{t("connectors.title")}</h1>
          <p className="text-muted-foreground max-w-3xl">
            {t("connectors.description")}
          </p>
        </header>

        <Card>
          <CardHeader>
            <CardTitle>{t("connectors.importTitle")}</CardTitle>
            <CardDescription>
              {t("connectors.importDescription")}
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid gap-4 md:grid-cols-[2fr_1fr_auto]">
              <Input
                value={url}
                onChange={(e) => setUrl(e.target.value)}
                placeholder={t("connectors.urlPlaceholder")}
                aria-label={t("connectors.urlPlaceholder")}
              />
              <Input
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder={t("connectors.namePlaceholder")}
                aria-label={t("connectors.namePlaceholder")}
              />
              <Button
                onClick={() =>
                  importMutation.mutate({
                    url: url.trim(),
                    name: name.trim() || undefined,
                  })
                }
                disabled={!url.trim() || importMutation.isPending}
                className="gap-2"
              >
                <ArrowRight className="h-4 w-4" />
                {importMutation.isPending
                  ? t("connectors.importing")
                  : t("connectors.importButton")}
              </Button>
            </div>
          </CardContent>
        </Card>

        {connector ? (
          <div className="grid gap-6 lg:grid-cols-[320px_minmax(0,1fr)]">
            <Card className="h-fit">
              <CardHeader className="space-y-3">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <CardTitle>{connector.name}</CardTitle>
                    <CardDescription>{connector.sourceUrl}</CardDescription>
                  </div>
                  <Badge variant="secondary">
                    {connector.specVersion ?? "API"}
                  </Badge>
                </div>
                <div className="flex flex-wrap gap-2">
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => refreshMutation.mutate(connector.id)}
                    disabled={refreshMutation.isPending}
                    className="gap-2"
                  >
                    <RefreshCw className="h-4 w-4" />
                    {t("connectors.refresh")}
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() =>
                      ipc.system.openExternalUrl(connector.sourceUrl)
                    }
                    className="gap-2"
                  >
                    <ExternalLink className="h-4 w-4" />
                    {t("connectors.openSpec")}
                  </Button>
                  <Button
                    size="sm"
                    variant="destructive"
                    onClick={() => deleteMutation.mutate(connector.id)}
                    disabled={deleteMutation.isPending}
                    className="gap-2"
                  >
                    <Trash2 className="h-4 w-4" />
                    {t("connectors.delete")}
                  </Button>
                </div>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div className="rounded-xl border p-3">
                    <div className="text-muted-foreground">
                      {t("connectors.endpointCount")}
                    </div>
                    <div className="text-2xl font-semibold">
                      {connector.endpoints.length}
                    </div>
                  </div>
                  <div className="rounded-xl border p-3">
                    <div className="text-muted-foreground">
                      {t("connectors.lastSynced")}
                    </div>
                    <div className="text-sm font-medium">
                      {connector.lastSyncedAt
                        ? new Date(connector.lastSyncedAt).toLocaleString()
                        : t("connectors.neverSynced")}
                    </div>
                  </div>
                </div>

                {connector.description ? (
                  <Textarea
                    readOnly
                    value={connector.description}
                    className="min-h-[120px] resize-none"
                  />
                ) : null}
              </CardContent>
            </Card>

            <div className="space-y-4">
              {groupedEndpoints.map(([tag, endpoints]) => (
                <Card key={tag}>
                  <CardHeader>
                    <CardTitle className="text-lg">{tag}</CardTitle>
                    <CardDescription>
                      {endpoints.length} {t("connectors.endpointsLabel")}
                    </CardDescription>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    {endpoints.map((endpoint) => (
                      <div
                        key={endpoint.id}
                        className="rounded-2xl border p-4 space-y-2"
                      >
                        <div className="flex items-center gap-3 flex-wrap">
                          <Badge variant="outline">{endpoint.method}</Badge>
                          <code className="text-sm">{endpoint.path}</code>
                        </div>
                        {endpoint.summary ? (
                          <div className="font-medium">{endpoint.summary}</div>
                        ) : null}
                        {endpoint.description ? (
                          <p className="text-sm text-muted-foreground whitespace-pre-wrap">
                            {endpoint.description}
                          </p>
                        ) : null}
                        {endpoint.operationId ? (
                          <div className="text-xs text-muted-foreground">
                            operationId: <code>{endpoint.operationId}</code>
                          </div>
                        ) : null}
                      </div>
                    ))}
                  </CardContent>
                </Card>
              ))}
            </div>
          </div>
        ) : (
          <Card>
            <CardContent className="py-16 text-center text-muted-foreground">
              {loading ? t("connectors.loading") : t("connectors.emptyState")}
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}
