import { useEffect, useMemo, useState } from "react";
import {
  Alert,
  Badge,
  Button,
  Code,
  Container,
  Group,
  Paper,
  Select,
  Stack,
  Table,
  Text,
  Title,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { IconAlertCircle, IconCategory } from "@tabler/icons-react";
import { AxiosError } from "axios";
import { apiClient } from "../lib/api";
import type { CatalogInfo, WhatsAppAccountConfig } from "../types";

function toPrettyJSON(value: unknown): string {
  return JSON.stringify(value, null, 2);
}

function extractErrorPayload(error: unknown): unknown {
  if (error instanceof AxiosError) return error.response?.data ?? { message: error.message };
  if (error instanceof Error) return { message: error.message };
  return { message: "Request failed" };
}

function formatError(error: unknown): string {
  if (error instanceof AxiosError) {
    if (typeof error.response?.data === "string") return error.response.data;
    if (error.response?.data && typeof error.response.data === "object") return toPrettyJSON(error.response.data);
    return error.message;
  }
  if (error instanceof Error) return error.message;
  return "Request failed";
}

export default function CatalogManagementPage() {
  const [accounts, setAccounts] = useState<WhatsAppAccountConfig[]>([]);
  const [loadingAccounts, setLoadingAccounts] = useState(true);
  const [accountId, setAccountId] = useState("");
  const [catalogs, setCatalogs] = useState<CatalogInfo[]>([]);
  const [loading, setLoading] = useState(false);

  const [responseHistory, setResponseHistory] = useState<
    Array<{
      id: string;
      title: string;
      status: "success" | "error";
      payload: unknown;
      createdAt: string;
    }>
  >([]);

  const businessAccounts = useMemo(
    () =>
      accounts
        .filter((entry) => entry.type === "business-api" && !entry.disabled)
        .sort((a, b) => a.id.localeCompare(b.id, undefined, { sensitivity: "base" })),
    [accounts],
  );

  const accountOptions = businessAccounts.map((entry) => ({
    value: entry.id,
    label: `${entry.id} (business-api)`,
  }));

  useEffect(() => {
    const loadAccounts = async () => {
      try {
        setLoadingAccounts(true);
        const result = await apiClient.getAccountConfigs();
        setAccounts(result || []);
      } catch {
        notifications.show({ title: "Error", message: "Failed to load accounts", color: "red" });
      } finally {
        setLoadingAccounts(false);
      }
    };
    loadAccounts();
  }, []);

  useEffect(() => {
    if (!accountId && businessAccounts.length > 0) {
      setAccountId(businessAccounts[0].id);
    }
  }, [businessAccounts, accountId]);

  const appendResponse = (entry: { title: string; status: "success" | "error"; payload: unknown }) => {
    const item = {
      id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
      createdAt: new Date().toISOString(),
      ...entry,
    };
    setResponseHistory((prev) => [item, ...prev].slice(0, 20));
    if (entry.status === "success") {
      console.info(`[Catalogs] ${entry.title} success`, entry.payload);
    } else {
      console.error(`[Catalogs] ${entry.title} error`, entry.payload);
    }
  };

  const handleListCatalogs = async () => {
    if (!accountId) {
      notifications.show({ title: "Validation Error", message: "Select a business account", color: "red" });
      return;
    }

    try {
      setLoading(true);
      const response = await apiClient.listCatalogs(accountId);
      setCatalogs(response.data || []);
      appendResponse({ title: "List Catalogs", status: "success", payload: response });
      notifications.show({ title: "Success", message: `Loaded ${response.data?.length || 0} catalogs`, color: "green" });
    } catch (error) {
      appendResponse({ title: "List Catalogs", status: "error", payload: extractErrorPayload(error) });
      notifications.show({ title: "Request Failed", message: formatError(error), color: "red" });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Container size="xl" py="xl">
      <Stack gap="lg">
        <div>
          <Title order={2}>Catalog Management</Title>
          <Text c="dimmed" size="sm">
            List catalogs for a selected WhatsApp Business account.
          </Text>
        </div>

        <Paper withBorder p="md">
          <Stack gap="sm">
            <Group justify="space-between">
              <Text fw={600}>Business Account</Text>
              <Badge variant="light" color="blue">
                {businessAccounts.length} business account(s)
              </Badge>
            </Group>
            <Select
              label="Account"
              data={accountOptions}
              value={accountId}
              onChange={(value) => setAccountId(value || "")}
              searchable
              disabled={loadingAccounts}
              placeholder="Select an account"
            />
            {businessAccounts.length === 0 && !loadingAccounts && (
              <Alert icon={<IconAlertCircle size={16} />} color="yellow" title="No Business API Accounts">
                No enabled `business-api` accounts were found.
              </Alert>
            )}
            <Button onClick={handleListCatalogs} loading={loading} disabled={!accountId}>
              List Catalogs
            </Button>
          </Stack>
        </Paper>

        <Paper withBorder p="md">
          <Stack>
            <Text fw={600}>Catalogs</Text>
            <Table withTableBorder withColumnBorders>
              <Table.Thead>
                <Table.Tr>
                  <Table.Th>Name</Table.Th>
                  <Table.Th>Product Count</Table.Th>
                  <Table.Th>Catalog ID</Table.Th>
                </Table.Tr>
              </Table.Thead>
              <Table.Tbody>
                {catalogs.length === 0 ? (
                  <Table.Tr>
                    <Table.Td colSpan={3}>
                      <Group justify="center" py="md">
                        <IconCategory size={20} />
                        <Text c="dimmed">No catalogs loaded yet.</Text>
                      </Group>
                    </Table.Td>
                  </Table.Tr>
                ) : (
                  catalogs.map((catalog) => (
                    <Table.Tr key={catalog.id}>
                      <Table.Td>{catalog.name || "-"}</Table.Td>
                      <Table.Td>{catalog.product_count ?? "-"}</Table.Td>
                      <Table.Td>
                        <Code>{catalog.id}</Code>
                      </Table.Td>
                    </Table.Tr>
                  ))
                )}
              </Table.Tbody>
            </Table>
          </Stack>
        </Paper>

        {responseHistory.length > 0 && (
          <Stack gap="sm">
            <Group justify="space-between">
              <Text fw={600}>Response History</Text>
              <Button variant="subtle" color="gray" size="xs" onClick={() => setResponseHistory([])}>
                Clear
              </Button>
            </Group>
            {responseHistory.map((entry) => (
              <Paper key={entry.id} withBorder p="md">
                <Text fw={600} size="sm" mb="xs">
                  {`${entry.title} - ${entry.status.toUpperCase()} - ${new Date(entry.createdAt).toLocaleString()}`}
                </Text>
                <Code block>{toPrettyJSON(entry.payload)}</Code>
              </Paper>
            ))}
          </Stack>
        )}
      </Stack>
    </Container>
  );
}
