"use client"

import { useMemo, useState } from "react"
import { PageHeader } from "@/components/page-header"
import { DataPageCard } from "@/components/data-page-card"
import { DataPageToolbar } from "@/components/data-page-toolbar"
import { DomainsDataGrid } from "@/components/data-grids/domains-data-grid"
import { FileImportDialog } from "@/components/file-import-dialog"
import { domains as mockDomains } from "@/lib/data"
import { Button } from "@/components/ui/button"
import { UploadIcon, DownloadIcon, PlusIcon, LoaderCircleIcon } from "lucide-react"
import { useDataSource } from "@/lib/data-source"
import { useEvoBGP } from "@/lib/evobgp-context"
import { cn } from "@/lib/utils"
import { toast } from "sonner"

export default function DomainsPage() {
  const { mode } = useDataSource()
  const { enabled, snapshot, loading, error } = useEvoBGP()
  const [importOpen, setImportOpen] = useState(false)
  const [search, setSearch] = useState("")

  const useEvoCatalog = mode === "live" && enabled

  const rows = useMemo(() => {
    if (!useEvoCatalog) return mockDomains
    if (loading && !snapshot) return []
    return snapshot?.domains ?? []
  }, [useEvoCatalog, loading, snapshot])

  const filtered = useMemo(() => {
    if (!search) return rows
    const q = search.toLowerCase()
    return rows.filter(
      (r) =>
        r.domain.toLowerCase().includes(q) ||
        r.asn.toLowerCase().includes(q) ||
        r.filter.toLowerCase().includes(q),
    )
  }, [rows, search])

  return (
    <div className="flex flex-col h-full">
      <PageHeader
        crumbs={[{ label: "Данные" }, { label: "Домены" }]}
        actions={
          <>
            <Button variant="outline" size="sm" onClick={() => setImportOpen(true)}>
              <UploadIcon className="size-4" />Импорт
            </Button>
            <Button variant="outline" size="sm"><DownloadIcon className="size-4" />Экспорт</Button>
            <Button size="sm"><PlusIcon className="size-4" />Добавить домен</Button>
          </>
        }
      />
      <div className="flex-1 overflow-y-auto p-6">
        <div className="flex flex-col gap-4">
          <div>
            <h1 className="text-2xl font-semibold tracking-tight">Домены</h1>
            <p className="text-sm text-muted-foreground mt-1">
              Отслеживаемые домены для BGP-фильтрации — синхронизируются в address-list MikroTik
            </p>
            {useEvoCatalog && (
              <p className={cn(
                "text-xs mt-2 flex items-center gap-1.5",
                error ? "text-destructive" : "text-muted-foreground",
              )}>
                {loading && <LoaderCircleIcon className="size-3.5 animate-spin shrink-0" />}
                {error
                  ? `EvoBGP: ${error}`
                  : snapshot?.fetchedAt
                    ? `Источник: EvoBGP, обновлено ${new Date(snapshot.fetchedAt).toLocaleString("ru-RU")}`
                    : loading ? "Загрузка EvoBGP…" : "EvoBGP"}
              </p>
            )}
          </div>
          <DataPageCard>
            <DataPageToolbar
              search={search}
              onSearchChange={setSearch}
              searchPlaceholder="Поиск по домену…"
              countLabel={`${filtered.length} доменов`}
            />
            <DomainsDataGrid
              domains={filtered}
              isLoading={useEvoCatalog && loading && !snapshot}
              pagination={useEvoCatalog}
            />
          </DataPageCard>
        </div>
      </div>
      <FileImportDialog
        open={importOpen}
        onOpenChange={setImportOpen}
        title="Импорт доменов"
        description="Загрузите CSV или JSON со списком доменов"
        accept=".csv,.json,text/csv,application/json"
        onImport={async (files) => {
          toast.info(`Выбран файл: ${files[0]?.name ?? "—"}`)
        }}
      />
    </div>
  )
}
