"use client";

import type { RedirectEvent } from "@domainops/shared-types";
import { App, Button, Table, Tag, Tooltip, Typography } from "antd";
import { EditOutlined, PlusOutlined } from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { listRedirects } from "@/lib/api/redirects";
import { ApiError } from "@/lib/api/client";
import { PageGuide } from "@/components/features/PageGuide";
import { REDIRECTS_GUIDES } from "@/lib/guides/redirects";
import { SORT_DIRECTIONS, textCompare } from "@/lib/utils/sort";
import { PAGE_SIZE_OPTIONS } from "@/lib/hooks/useServerPagination";
import { BulkRedirectModal } from "./BulkRedirectModal";
import { RedirectQuickEditModal } from "./RedirectQuickEditModal";

export default function RedirectsPage() {
  const { message } = App.useApp();
  const [redirects, setRedirects] = useState<RedirectEvent[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isBulkOpen, setIsBulkOpen] = useState(false);
  const [quickEditDomainId, setQuickEditDomainId] = useState<number | null>(null);

  const load = useCallback(async () => {
    setIsLoading(true);
    try {
      setRedirects(await listRedirects());
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't load redirects.");
    } finally {
      setIsLoading(false);
    }
  }, [message]);

  useEffect(() => {
    // Redirects live on the Laravel API - a client fetch on mount, not a
    // state-sync bug.
    // eslint-disable-next-line react-hooks/set-state-in-effect
    void load();
  }, [load]);

  const columns: ColumnsType<RedirectEvent> = [
    {
      title: "From",
      sorter: (a, b) => textCompare(a.source_domain?.fqdn, b.source_domain?.fqdn),
      sortDirections: SORT_DIRECTIONS,
      render: (_, redirect) =>
        redirect.source_domain ? (
          <Link href={`/domains/${redirect.source_domain.id}`} className="font-mono">
            {redirect.source_domain.fqdn}
          </Link>
        ) : (
          "—"
        ),
    },
    {
      title: "To",
      dataIndex: "target_url",
      sorter: (a, b) => textCompare(a.target_url, b.target_url),
      sortDirections: SORT_DIRECTIONS,
      render: (v: string) => <span className="font-mono">{v}</span>,
    },
    { title: "Type", dataIndex: "type", render: (v: string) => <Tag>{v}</Tag> },
    {
      title: "Scope",
      render: (_, redirect) =>
        redirect.path_pattern ? (
          <span>
            Path <span className="font-mono">{redirect.path_pattern}</span>
          </span>
        ) : (
          "Whole Domain"
        ),
    },
    {
      title: "Since",
      dataIndex: "created_at",
      render: (v: string) => new Date(v).toLocaleDateString(),
    },
    {
      title: "Actions",
      render: (_, redirect) => (
        <Tooltip title="Quick edit">
          <Button
            size="small"
            icon={<EditOutlined />}
            onClick={() => {
              setQuickEditDomainId(redirect.source_domain_id);
              setIsModalOpen(true);
            }}
            className="dms_redirects_quick_edit_btn"
          />
        </Tooltip>
      ),
    },
  ];

  return (
    <div className="flex flex-col gap-4 page page-redirects">
      <div className="flex items-center justify-between flex-wrap gap-2">
        <div className="flex items-center gap-2">
          <Typography.Title level={4} style={{ margin: 0 }}>
            Redirects
          </Typography.Title>
          <PageGuide guides={REDIRECTS_GUIDES} label="Redirects guide" />
        </div>
        <div className="flex gap-2">
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setQuickEditDomainId(null);
              setIsModalOpen(true);
            }}
            className="dms_redirects_add_btn"
          >
            Add Redirect
          </Button>
          <Button onClick={() => setIsBulkOpen(true)} className="dms_redirects_bulk_add_btn">
            Bulk Add
          </Button>
          <Link href="/redirects/map">
            <Button className="dms_redirects_view_map_btn">View Map</Button>
          </Link>
        </div>
      </div>
      <Typography.Paragraph type="secondary">
        Every active redirect, set on Cloudflare. Add one for any domain or subdomain in Domain Inventory, or use quick edit to change an existing one.
      </Typography.Paragraph>
      <Table<RedirectEvent>
        rowKey="id"
        columns={columns}
        dataSource={redirects}
        loading={isLoading}
        pagination={{ showSizeChanger: true, pageSizeOptions: PAGE_SIZE_OPTIONS, showTotal: (count) => `${count} redirects` }}
        className="dms_redirects_table"
      />
      <RedirectQuickEditModal
        open={isModalOpen}
        domainId={quickEditDomainId}
        onClose={() => setIsModalOpen(false)}
        onChanged={() => void load()}
      />
      <BulkRedirectModal open={isBulkOpen} onClose={() => setIsBulkOpen(false)} onDone={() => void load()} />
    </div>
  );
}
