"use client";

import { useCallback, useEffect, useState } from "react";
import { Button, Card, Col, List, Row, Space, Statistic, Tag, Typography, message } from "antd";
import dayjs from "dayjs";
import { useRouter } from "next/navigation";

import { PageStateNotice } from "@/components/common/page-state-notice";
import { fetchCaasmAssets, fetchCaasmDomainStats, fetchCaasmPortStats } from "@/lib/api/caasm";
import type { CaasmAssetRecord, CaasmDomainStats, CaasmPortStats } from "@/types/models";

const { Title, Paragraph, Text } = Typography;

export default function CaasmOverviewPage() {
  const router = useRouter();
  const [assetTotal, setAssetTotal] = useState(0);
  const [recentAssets, setRecentAssets] = useState<CaasmAssetRecord[]>([]);
  const [portStats, setPortStats] = useState<CaasmPortStats | null>(null);
  const [domainStats, setDomainStats] = useState<CaasmDomainStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [failedSources, setFailedSources] = useState<string[]>([]);

  const loadOverview = useCallback(async () => {
    setLoading(true);
    const nextFailures: string[] = [];

    try {
      const assetPayload = await fetchCaasmAssets({ page: 1, page_size: 5 });
      setAssetTotal(assetPayload.total ?? 0);
      setRecentAssets(assetPayload.items ?? []);
    } catch (error) {
      nextFailures.push("assets");
      console.error("Failed to load CAASM overview assets", error);
      message.error("Failed to load asset summary");
      setRecentAssets([]);
    }
    try {
      const ports = await fetchCaasmPortStats();
      setPortStats(ports);
    } catch (error) {
      nextFailures.push("ports");
      console.error("Failed to load port stats", error);
      setPortStats(null);
    }
    try {
      const domains = await fetchCaasmDomainStats();
      setDomainStats(domains);
    } catch (error) {
      nextFailures.push("domains");
      console.error("Failed to load domain stats", error);
      setDomainStats(null);
    } finally {
      setFailedSources(nextFailures);
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    async function bootstrap() {
      try {
        await loadOverview();
      } catch {
        // Individual loaders already handle operator-facing feedback.
      }
    }
    bootstrap();
  }, [loadOverview]);

  const kpiCards = [
    {
      title: "Assets in inventory",
      value: assetTotal,
      detail: "Across all onboarded accounts",
      href: "/dashboard/caasm/assets",
      action: "Open Assets",
    },
    {
      title: "Open ports",
      value: portStats?.total ?? 0,
      detail: portStats ? `${portStats.public} public` : "No stats yet",
      href: "/dashboard/caasm/ports",
      action: "Open Ports",
    },
    {
      title: "Domains tracked",
      value: domainStats?.total ?? 0,
      detail: domainStats ? `${domainStats.expiring_soon} expiring soon` : "No data",
      href: "/dashboard/caasm/domains",
      action: "Open Domains",
    },
    {
      title: "Expiring domains",
      value: domainStats?.expiring_soon ?? 0,
      detail: "Next 30 days",
      href: "/dashboard/caasm/domains",
      action: "Review Expiring Domains",
    },
  ];

  const hasAnyOverviewData = assetTotal > 0 || recentAssets.length > 0 || portStats !== null || domainStats !== null;

  return (
    <Space direction="vertical" size={24} style={{ width: "100%" }}>
      <div>
        <Title level={3} style={{ marginBottom: 4 }}>
          CAASM Overview
        </Title>
        <Paragraph type="secondary" style={{ marginBottom: 0 }}>
          Unified summary of assets, open ports, and discovery signals.
        </Paragraph>
      </div>

      {!hasAnyOverviewData && (
        <Card>
          <PageStateNotice
            tone={loading ? "loading" : failedSources.length > 0 ? "unavailable" : "empty"}
            title={
              loading
                ? "Loading CAASM overview"
                : failedSources.length > 0
                  ? "CAASM overview is partially unavailable"
                  : "No CAASM overview data yet"
            }
            description={
              loading
                ? "Fetching the latest asset, port, and domain summaries."
                : failedSources.length > 0
                  ? `Unavailable sources: ${failedSources.join(", ")}. Retry the overview or review the underlying CAASM pages directly.`
                  : "Run or review a CAASM sync to populate overview cards, recent assets, and port/domain summaries."
            }
            actions={
              <Space wrap>
                <Button onClick={() => void loadOverview()} disabled={loading}>
                  Refresh overview
                </Button>
                <Button type="primary" href="/dashboard/caasm/cloud-accounts">
                  Review cloud accounts
                </Button>
              </Space>
            }
          />
        </Card>
      )}

      <Row gutter={[16, 16]}>
        {kpiCards.map((card) => (
          <Col xs={24} md={6} key={card.title}>
            <Card hoverable onClick={() => router.push(card.href)} style={{ cursor: "pointer", height: "100%" }}>
              <Space direction="vertical" size={8} style={{ width: "100%" }}>
                <Statistic title={card.title} value={card.value} />
                <Paragraph type="secondary" style={{ marginBottom: 0 }}>
                  {card.detail}
                </Paragraph>
                <Button type="link" href={card.href} style={{ padding: 0, width: "fit-content" }}>
                  {card.action}
                </Button>
              </Space>
            </Card>
          </Col>
        ))}
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} md={12}>
          <Card title="Newest assets">
            {recentAssets.length > 0 ? (
              <List
                dataSource={recentAssets}
                renderItem={(item) => (
                  <List.Item>
                    <Space direction="vertical" size={0} style={{ width: "100%" }}>
                      <Space align="center" size={8} wrap>
                        <Text strong>{item.name}</Text>
                        <Button type="link" href="/dashboard/caasm/assets" style={{ padding: 0, height: "auto" }}>
                          Open Assets
                        </Button>
                      </Space>
                      <Space size={8}>
                        <Tag>{item.asset_type?.toUpperCase()}</Tag>
                        {item.environment && <Tag color="blue">{item.environment.toUpperCase()}</Tag>}
                        {item.cloud_account?.name && <Tag color="purple">{item.cloud_account.name}</Tag>}
                      </Space>
                      <Text type="secondary">Seen {item.last_seen_at ? dayjs(item.last_seen_at).format("YYYY-MM-DD") : "recently"}</Text>
                    </Space>
                  </List.Item>
                )}
              />
            ) : (
              <PageStateNotice
                tone={loading ? "loading" : "empty"}
                compact
                title={loading ? "Loading newest assets" : "No recent assets available"}
                description={
                  loading
                    ? "Waiting for the latest inventory snapshot."
                    : "Open the asset inventory or re-run a CAASM sync if you expect recently seen assets here."
                }
                actions={
                  <Space wrap>
                    <Button href="/dashboard/caasm/assets">Open assets</Button>
                    <Button type="primary" href="/dashboard/caasm/cloud-accounts">
                      Review cloud accounts
                    </Button>
                  </Space>
                }
              />
            )}
          </Card>
        </Col>
        <Col xs={24} md={12}>
          <Card title="Top open ports">
            {portStats?.top_open_ports?.length ? (
              <List
                dataSource={portStats.top_open_ports}
                renderItem={(entry) => (
                  <List.Item>
                    <Space style={{ width: "100%", justifyContent: "space-between" }}>
                      <Text>Port {entry.port}</Text>
                      <Tag>{entry.count}</Tag>
                    </Space>
                  </List.Item>
                )}
              />
            ) : (
              <Space direction="vertical" size={8}>
                <Paragraph type="secondary" style={{ marginBottom: 0 }}>
                  No open port data yet.
                </Paragraph>
                <Button type="link" href="/dashboard/caasm/ports" style={{ padding: 0, width: "fit-content" }}>
                  Open Ports
                </Button>
              </Space>
            )}
          </Card>
        </Col>
      </Row>

    </Space>
  );
}
