"use client"

import { toastApiError } from "@/lib/toast-api-error";
import Link from "next/link"
import { ArrowLeft, Eye, Loader2, Trash2 } from "lucide-react"
import * as React from "react"
import { toast } from "sonner"

import { Button } from "@/components/ui/button"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  addDeepdexVisibility,
  deleteDeepdexVisibility,
  downloadDeepdexDocument,
  fetchDeepdexVisibilityPage,
} from "@/components/deepdex/api/deepdex.api"
import { getDeepdexDocTypeLabel } from "@/components/deepdex/data/deepdex-doc-types"
import { DeepdexVisibilityRmList } from "@/components/deepdex/components/deepdex-visibility-rm-list"
import { DeepdexVisibilitySourceBadge } from "@/components/deepdex/components/deepdex-visibility-source-badge"
import type { DeepdexDocument, DeepdexVisibilityRow } from "@/components/deepdex/types"
import { ListPageCard } from "@/app/dashboard/_components"
import { SettingsSelect } from "@/components/settings/ui/settings-select"
import { TABLE_TOOLBAR_BTN, TABLE_TOOLBAR_BTN_OUTLINE } from "@/components/shared/table-ui"

type DeepdexVisibilityPageProps = {
  documentId: string
}

export function DeepdexVisibilityPage({ documentId }: DeepdexVisibilityPageProps) {
  const [document, setDocument] = React.useState<DeepdexDocument | null>(null)
  const [rows, setRows] = React.useState<DeepdexVisibilityRow[]>([])
  const [customers, setCustomers] = React.useState<{ id: number; label: string }[]>([])
  const [customerId, setCustomerId] = React.useState("0")
  const [isLoading, setIsLoading] = React.useState(true)
  const [isAdding, setIsAdding] = React.useState(false)

  const load = React.useCallback(async () => {
    setIsLoading(true)
    try {
      const data = await fetchDeepdexVisibilityPage(documentId)
      setDocument(data.document)
      setRows(data.rows)
      setCustomers(data.customers)
    } catch {
      toast.error("Failed to load visibility")
    } finally {
      setIsLoading(false)
    }
  }, [documentId])

  React.useEffect(() => {
    void load()
  }, [load])

  const handleAdd = async (e: React.FormEvent) => {
    e.preventDefault()
    const id = Number(customerId)
    if (!id) {
      toast.error("Select a customer")
      return
    }
    setIsAdding(true)
    try {
      const row = await addDeepdexVisibility(documentId, id, customers)
      if (row) {
        setRows((prev) => [...prev, row])
        setCustomerId("0")
        toast.success("Visibility added")
        if (document) {
          setDocument({ ...document, visibilityCount: document.visibilityCount + 1 })
        }
      }
    } catch (error) {
      toastApiError(error, "Failed to add visibility")
    } finally {
      setIsAdding(false)
    }
  }

  const handleRemove = async (visibilityId: string) => {
    try {
      await deleteDeepdexVisibility(documentId, visibilityId)
      setRows((prev) => prev.filter((r) => r.id !== visibilityId))
      if (document) {
        setDocument({
          ...document,
          visibilityCount: Math.max(0, document.visibilityCount - 1),
        })
      }
      toast.success("Visibility removed")
    } catch {
      toast.error("Failed to remove visibility")
    }
  }

  const headerActions = document ? (
    <div className="flex flex-wrap items-center gap-2">
      <Button {...TABLE_TOOLBAR_BTN_OUTLINE} asChild>
        <Link href="/dashboard/deepdex/view-all">
          <ArrowLeft className="size-4" />
          Back to list
        </Link>
      </Button>
      <Button
        {...TABLE_TOOLBAR_BTN_OUTLINE}
        disabled={!document.downloadToken}
        onClick={() => {
          if (!document.downloadToken) {
            toast.error("View token is unavailable")
            return
          }
          void downloadDeepdexDocument(document.downloadToken, document.originalName)
        }}
      >
        <Eye className="size-4" />
        View document
      </Button>
    </div>
  ) : (
    <Button {...TABLE_TOOLBAR_BTN_OUTLINE} asChild>
      <Link href="/dashboard/deepdex/view-all">
        <ArrowLeft className="size-4" />
        Back to list
      </Link>
    </Button>
  )

  if (isLoading) {
    return (
      <ListPageCard icon={Eye} title="Visibility" actions={headerActions}>
        <p className="text-sm text-muted-foreground">Loading…</p>
      </ListPageCard>
    )
  }

  if (!document) {
    return (
      <ListPageCard icon={Eye} title="Visibility" actions={headerActions}>
        <p className="text-sm text-muted-foreground">Document not found.</p>
      </ListPageCard>
    )
  }

  return (
    <ListPageCard
      icon={Eye}
      title="Visibility"
      description={
        <>
          Document: <strong>{document.originalName}</strong> (ID: {document.id},{" "}
          {getDeepdexDocTypeLabel(document.docType)}, {document.fileVersion})
        </>
      }
      breadcrumb={[
        { label: "Deepdex", href: "/dashboard/deepdex/view-all" },
        { label: "Visibility" },
      ]}
      actions={headerActions}
    >
      <div className="space-y-6">
          <div>
            <h3 className="mb-3 text-base font-semibold">Add visibility</h3>
            <form
              onSubmit={(e) => void handleAdd(e)}
              className="flex max-w-md flex-col gap-3 sm:flex-row sm:items-end"
            >
              <div className="flex-1 space-y-1.5">
                <label htmlFor="add-customer" className="text-sm font-medium">
                  Customer
                </label>
                <SettingsSelect
                  value={customerId}
                  onValueChange={setCustomerId}
                  options={[
                    { value: "0", label: "— Select customer —" },
                    ...customers.map((c) => ({
                      value: String(c.id),
                      label: c.label,
                    })),
                  ]}
                />
              </div>
              <Button type="submit" {...TABLE_TOOLBAR_BTN} disabled={isAdding}>
                {isAdding ? (
                  <Loader2 className="size-4 animate-spin" />
                ) : (
                  "Add"
                )}
              </Button>
            </form>
            <p className="mt-2 text-sm text-muted-foreground">
              Document will be visible to this customer and to their assigned RM.
            </p>
          </div>

          <div>
            <h3 className="mb-3 text-base font-semibold">Current visibility</h3>
            <div className="rounded-lg border">
              <Table>
                <TableHeader>
                  <TableRow className="bg-muted/40">
                    <TableHead className="w-16">ID</TableHead>
                    <TableHead className="w-28">User type</TableHead>
                    <TableHead className="w-[14rem]">User</TableHead>
                    <TableHead>RM</TableHead>
                    <TableHead className="w-32">Source</TableHead>
                    <TableHead className="w-36">Created</TableHead>
                    <TableHead className="w-20 text-right">Remove</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {rows.length ? (
                    rows.map((row) => (
                      <TableRow key={row.id} className="align-top">
                        <TableCell className="font-mono text-sm">{row.id}</TableCell>
                        <TableCell>{row.userType}</TableCell>
                        <TableCell className="max-w-[14rem]">
                          <span className="line-clamp-2 text-sm" title={row.userDisplay}>
                            {row.userDisplay}
                          </span>
                        </TableCell>
                        <TableCell>
                          <DeepdexVisibilityRmList names={row.rmNames} />
                        </TableCell>
                        <TableCell>
                          <DeepdexVisibilitySourceBadge source={row.source} />
                        </TableCell>
                        <TableCell className="whitespace-nowrap text-sm text-muted-foreground">
                          {new Date(row.createdAt).toLocaleString("en-GB", {
                            day: "2-digit",
                            month: "2-digit",
                            year: "numeric",
                            hour: "2-digit",
                            minute: "2-digit",
                          })}
                        </TableCell>
                        <TableCell className="text-right">
                          <Button
                            type="button"
                            variant="destructive"
                            size="icon"
                            className="size-7"
                            onClick={() => void handleRemove(row.id)}
                          >
                            <Trash2 className="size-3.5" />
                            <span className="sr-only">Remove</span>
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell
                        colSpan={7}
                        className="h-20 text-center text-muted-foreground"
                      >
                        No visibility records.
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>
          </div>
      </div>
    </ListPageCard>
  )
}
