"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import {
  Badge,
  Button,
  Card,
  Col,
  Drawer,
  Form,
  Input,
  Row,
  Select,
  Space,
  Statistic,
  Table,
  Tag,
  Typography,
  message,
} from "antd";
import type { ColumnsType, TablePaginationConfig } from "antd/es/table";
import { ReloadOutlined } from "@ant-design/icons";
import dayjs from "dayjs";

import { fetchCaasmAssets, fetchCaasmAssetDetail, fetchCaasmServices, fetchCaasmEnvironments } from "@/lib/api/caasm";
import type { CaasmAssetDetail, CaasmAssetRecord, CaasmConfig } from "@/types/models";

const { Title, Paragraph, Text } = Typography;

const summarizeIPAddresses = (addresses?: string[]) => {
  const values = (addresses ?? []).filter(Boolean);
  return {
    values,
    primary: values[0],
    overflow: Math.max(values.length - 2, 0),
  };
};

const assetDisplayName = (record: CaasmAssetRecord) =>
  record.name || record.native_id || summarizeIPAddresses(record.ip_addresses).primary || `#${record.id}`;

const statusOptions = [
  { label: "Active", value: "active" },
  { label: "Inactive", value: "inactive" },
];

const criticalityColors: Record<string, string> = {
  critical: "red",
  high: "volcano",
  medium: "gold",
  low: "blue",
};

const providerOptions = [
  { label: "AWS", value: "aws" },
  { label: "GCP", value: "gcp" },
  { label: "Azure", value: "azure" },
  { label: "Alibaba", value: "alibaba" },
  { label: "GoDaddy", value: "godaddy" },
  { label: "Other", value: "other" },
];

const providerColors: Record<string, string> = {
  aws: "gold",
  gcp: "red",
  azure: "blue",
  alibaba: "orange",
  godaddy: "purple",
  other: "default",
};

export default function CaasmAssetsPage() {
  const [records, setRecords] = useState<CaasmAssetRecord[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState<{
    q?: string;
    provider?: string;
    environment?: string;
    type?: string;
    status?: string;
    service?: string;
  }>({
    q: "",
  });
  const [pagination, setPagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 20 });
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [detail, setDetail] = useState<CaasmAssetDetail | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);
  const [selectedAsset, setSelectedAsset] = useState<CaasmAssetRecord | null>(null);
  const [serviceOptions, setServiceOptions] = useState<{ label: string; value: string }[]>([]);
  const [environmentOptions, setEnvironmentOptions] = useState<{ label: string; value: string }[]>([]);

  const loadData = useCallback(
    async (page: number, pageSize: number) => {
      setLoading(true);
      try {
        const payload = await fetchCaasmAssets({
          page,
          page_size: pageSize,
          q: filters.q || undefined,
          provider: filters.provider,
          environment: filters.environment,
          type: filters.type,
          status: filters.status,
          service: filters.service,
        });
        setRecords(payload.items ?? []);
        setTotal(payload.total ?? 0);
      } catch (error) {
        console.error("Failed to load CAASM assets", error);
        message.error("Failed to load assets");
      } finally {
        setLoading(false);
      }
    },
    [filters],
  );

  useEffect(() => {
    const current = pagination.current ?? 1;
    const size = pagination.pageSize ?? 20;
    loadData(current, size);
  }, [loadData, pagination]);

  useEffect(() => {
    fetchCaasmServices()
      .then(services => setServiceOptions(services.map(s => ({ label: s, value: s }))))
      .catch(console.error);
    fetchCaasmEnvironments()
      .then(environments => {
        const options = environments.map(e => ({ label: e, value: e }));
        // Add "Other" option for empty/null environment values
        options.push({ label: "other", value: "other" });
        setEnvironmentOptions(options);
      })
      .catch(console.error);
  }, []);



  const handleView = useCallback(
    async (record: CaasmAssetRecord) => {
      setSelectedAsset(record);
      setDrawerVisible(true);
      setDetailLoading(true);
      try {
        const payload = await fetchCaasmAssetDetail(record.id);
        setDetail(payload);
      } catch (error) {
        console.error("Failed to load asset detail", error);
        message.error("Failed to load asset detail");
      } finally {
        setDetailLoading(false);
      }
    },
    [],
  );

  const columns: ColumnsType<CaasmAssetRecord> = useMemo(
    () => [
      {
        title: "Name",
        dataIndex: "name",
        width: 280,
        render: (_, record) => {
          const displayName = assetDisplayName(record);
          return (
            <Space direction="vertical" size={4} style={{ maxWidth: "100%" }}>
              <Text strong ellipsis={{ tooltip: displayName }} style={{ display: "block", maxWidth: "100%" }}>
                {displayName}
              </Text>
              <Space size={4} wrap>
                <Text type="secondary" style={{ fontSize: 12 }}>
                  #{record.id}
                </Text>
                {record.name && record.native_id ? (
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    {record.native_id}
                  </Text>
                ) : null}
              </Space>
            </Space>
          );
        },
      },

      {
        title: "Service",
        dataIndex: "service",
        width: 140,
        onHeaderCell: () => ({ style: { whiteSpace: "nowrap" } }),
        render: (value: string) => (
          <Text ellipsis={{ tooltip: value }} style={{ maxWidth: 130, display: "inline-block" }}>
            {value || "—"}
          </Text>
        ),
      },
      {
        title: "Provider",
        dataIndex: ["cloud_account", "provider"],
        width: 110,
        onHeaderCell: () => ({ style: { whiteSpace: "nowrap" } }),
        render: (_, record) => {
          const provider = record.cloud_account?.provider?.toLowerCase();
          return (
            <span style={{ whiteSpace: "nowrap" }}>
              <Tag color={providerColors[provider || "other"] || "default"}>{provider ? provider.toUpperCase() : "—"}</Tag>
            </span>
          );
        },
      },
      {
        title: "Environment",
        dataIndex: "environment",
        width: 120,
        onHeaderCell: () => ({ style: { whiteSpace: "nowrap" } }),
        render: (value: string) => <span style={{ whiteSpace: "nowrap" }}>{value?.toUpperCase() ?? "—"}</span>,
      },
      {
        title: "Criticality",
        dataIndex: "criticality",
        width: 110,
        render: (value: string) => (
          <span style={{ whiteSpace: "nowrap" }}>
            <Tag color={criticalityColors[value] ?? "default"}>{value?.toUpperCase()}</Tag>
          </span>
        ),
      },
      {
        title: "Owner",
        dataIndex: "owner_employee_id",
        width: 200,
        ellipsis: {
          showTitle: false,
        },
        render: (_: unknown, record) => {
          const owner =
            record.owner_employee?.name ||
            record.owner_employee?.email ||
            "—";
          return (
            <Text ellipsis={{ tooltip: owner }} style={{ maxWidth: "100%" }}>
              {owner}
            </Text>
          );
        },
      },
      {
        title: "Last seen",
        dataIndex: "last_seen_at",
        width: 150,
        render: (value: string | undefined) => (
          <span style={{ whiteSpace: "nowrap" }}>{value ? dayjs(value).format("YYYY-MM-DD HH:mm") : "—"}</span>
        ),
      },
      {
        title: "Cloud Account",
        dataIndex: ["cloud_account", "name"],
        width: 220,
        render: (_, record) =>
          record.cloud_account ? (
            <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0, width: "100%" }}>
              <Badge status={record.cloud_account.status === "active" ? "success" : "default"} />
              <Text
                ellipsis={{ tooltip: record.cloud_account.name }}
                style={{ minWidth: 0, flex: 1, display: "block" }}
              >
                {record.cloud_account.name}
              </Text>
            </div>
          ) : (
            <Text type="secondary">Unassigned</Text>
          ),
      },
      {
        title: "Actions",
        dataIndex: "actions",
        width: 80,
        align: "center",
        onHeaderCell: () => ({ style: { whiteSpace: "nowrap" } }),
        render: (_, record) => (
          <Button size="small" type="link" onClick={() => handleView(record)} style={{ whiteSpace: "nowrap" }}>
            View
          </Button>
        ),
      },
    ],
    [handleView],
  );

  const handleTableChange = (next: TablePaginationConfig) => {
    setPagination(next);
  };

  const handleFilterChange = (field: string, value: string) => {
    setFilters((prev) => ({ ...prev, [field]: value || undefined }));
    setPagination((prev) => ({ ...prev, current: 1 }));
  };

  const handleReset = () => {
    setFilters({ q: "", provider: undefined, environment: undefined, type: undefined, status: undefined });
    setPagination({ current: 1, pageSize: pagination.pageSize });
  };

  return (
    <Space direction="vertical" size={24} style={{ width: "100%" }}>
      <Row gutter={[16, 16]}>
        <Col xs={24} md={16}>
          <Card>
            <Space direction="vertical" size={16} style={{ width: "100%" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <div>
                  <Title level={4} style={{ margin: 0 }}>
                    Asset inventory
                  </Title>
                  <Paragraph type="secondary" style={{ marginBottom: 0 }}>
                    Consolidated view across connected cloud accounts and discovery channels.
                  </Paragraph>
                </div>
                <Button icon={<ReloadOutlined />} onClick={() => loadData(pagination.current ?? 1, pagination.pageSize ?? 20)}>
                  Refresh
                </Button>
              </div>
              <Form layout="vertical">
                <Row gutter={16}>
                  <Col xs={24} md={8}>
                    <Form.Item label="Search">
                      <Input
                        placeholder="Hostname, owner, etc."
                        value={filters.q}
                        onChange={(event) => handleFilterChange("q", event.target.value)}
                        allowClear
                      />
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={4}>
                    <Form.Item label="Provider">
                      <Select
                        options={providerOptions}
                        allowClear
                        value={filters.provider}
                        onChange={(value) => handleFilterChange("provider", value)}
                      />
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={4}>
                    <Form.Item label="Environment">
                      <Select
                        options={environmentOptions}
                        allowClear
                        value={filters.environment}
                        onChange={(value) => handleFilterChange("environment", value)}
                      />
                    </Form.Item>
                  </Col>

                  <Col xs={24} md={4}>
                    <Form.Item label="Status">
                      <Select
                        options={statusOptions}
                        allowClear
                        value={filters.status}
                        onChange={(value) => handleFilterChange("status", value)}
                      />
                    </Form.Item>
                  </Col>
                  <Col xs={24} md={4}>
                    <Form.Item label="Service">
                      <Select
                        placeholder="Select service"
                        options={serviceOptions}
                        allowClear
                        value={filters.service}
                        onChange={(value) => handleFilterChange("service", value)}
                      />
                    </Form.Item>
                  </Col>
                </Row>
                <Button onClick={handleReset} type="link">
                  Reset filters
                </Button>
              </Form>
            </Space>
          </Card>
        </Col>
        <Col xs={24} md={8}>
          <Card>
            <Statistic title="Total assets" value={total} />
          </Card>
        </Col>
      </Row>

      <Card>
        <Table
          rowKey="id"
          loading={loading}
          dataSource={records}
          columns={columns}
          tableLayout="fixed"
          scroll={{ x: 1200 }}
          pagination={{ ...pagination, total }}
          onChange={handleTableChange}
        />
      </Card>

      <Drawer
        title={selectedAsset?.name || "Asset details"}
        open={drawerVisible}
        onClose={() => {
          setDrawerVisible(false);
          setDetail(null);
        }}
        width={640}
      >
        {detailLoading ? (
          <Paragraph>Loading...</Paragraph>
        ) : detail && detail.asset ? (
          <Space direction="vertical" size={16} style={{ width: "100%" }}>
            <Card size="small" title="Metadata">
              <Space direction="vertical" size={4}>
                <Text>
                  <Text strong>Service:</Text>{" "}
                  {detail.asset.service ||
                    detail.asset.asset_type?.toUpperCase() ||
                    "—"}
                </Text>
                <Text>
                  <Text strong>Criticality:</Text> {detail.asset.criticality || "—"}
                </Text>
                <Text>
                  <Text strong>Owner:</Text>{" "}
                  {detail.asset.owner_employee?.name ||
                    detail.asset.owner_employee?.email ||
                    "—"}
                </Text>
                <Text>
                  <Text strong>Environment:</Text> {detail.asset.environment || "—"}
                </Text>
                <Text>
                  <Text strong>Cloud account:</Text> {detail.asset.cloud_account?.name || "Unassigned"}
                </Text>
              </Space>
            </Card>
            <Card size="small" title={`IP addresses (${detail.ip_addresses.length})`}>
              {detail.ip_addresses.length === 0 ? (
                <Paragraph type="secondary">No IPs recorded</Paragraph>
              ) : (
                <Space direction="vertical" style={{ width: "100%" }}>
                  {detail.ip_addresses.map((ip) => (
                    <div key={ip.id} style={{ display: "flex", justifyContent: "space-between" }}>
                      <Text>{ip.ip_address}</Text>
                      <Tag color={ip.is_public ? "red" : "green"}>{ip.is_public ? "Public" : "Internal"}</Tag>
                    </div>
                  ))}
                </Space>
              )}
            </Card>
            <Card size="small" title={`Domains (${detail.domain_assets.length})`}>
              {detail.domain_assets.length === 0 ? (
                <Paragraph type="secondary">No domains linked</Paragraph>
              ) : (
                <Space direction="vertical" style={{ width: "100%" }}>
                  {detail.domain_assets.map((domain) => (
                    <div key={domain.id}>
                      <Text strong>{domain.domain_name}</Text>
                      <br />
                      <Text type="secondary">
                        Expires {domain.expires_at ? dayjs(domain.expires_at).format("YYYY-MM-DD") : "N/A"}
                      </Text>
                    </div>
                  ))}
                </Space>
              )}
            </Card>
            <Card size="small" title={`Relationships (${detail.relationships.length})`}>
              {detail.relationships.length === 0 ? (
                <Paragraph type="secondary">No relationships cataloged yet</Paragraph>
              ) : (
                <Space direction="vertical" style={{ width: "100%" }}>
                  {detail.relationships.map((rel) => (
                    <Text key={rel.id}>
                      {rel.source_asset_id} — {rel.relationship_type} → {rel.target_asset_id}
                    </Text>
                  ))}
                </Space>
              )}
            </Card>
          </Space>
        ) : (
          <Paragraph type="secondary">Select an asset to view details.</Paragraph>
        )
        }
      </Drawer >
    </Space >
  );
}
