'use client'

import { useCallback, useEffect, useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import { Eye, RefreshCw, Search, FileCheck2, Clock3, CheckCircle2 } from "lucide-react"
import { useTranslation } from "react-i18next"
import { useInboundPostings } from "@/hooks/useInboundPostings"
import { inboundPostingStatusLabel, inboundPostingStatusTone } from "@/lib/inbound-postings"
import type { InboundPostingFilters, InboundPostingListItem } from "@/types"
import { PageHeader } from "@/components/ui/page-header"
import { SectionCard } from "@/components/ui/section-card"
import { KpiCard } from "@/components/ui/kpi-card"
import { DataTable, type Column } from "@/components/ui/data-table"
import { StatusBadge } from "@/components/ui/status-badge"
import { Button } from "@/components/ui/button"
import { Pagination } from "@/components/ui/Pagination"
import { fmtGrams, formatDateTime } from "@/lib/format"

export default function InboundPostingsPage() {
  const router = useRouter()
  const { i18n } = useTranslation()
  const { items, total, pages, isLoading, error, list } = useInboundPostings()
  const [page, setPage] = useState(1)
  const [filters, setFilters] = useState<InboundPostingFilters>({ page: 1, page_size: 25 })

  const language = i18n.language.startsWith("ar") ? "ar" : "en"

  const refresh = useCallback(() => list({ ...filters, page }), [filters, list, page])
  useEffect(() => { refresh() }, [refresh])

  const openDetail = useCallback((id: string) => router.push(`/inbound-postings/${id}`), [router])

  const columns: Column<InboundPostingListItem>[] = [
    {
      key: "order",
      header: language === "ar" ? "رقم الاستلام" : "Receiving No",
      cell: row => <span className="font-mono font-semibold">{row.receiving_order_no}</span>,
    },
    {
      key: "weight",
      header: language === "ar" ? "الوزن" : "Weight",
      cell: row => <span className="font-mono">{fmtGrams(Number(row.total_weight_grams))}</span>,
    },
    {
      key: "status",
      header: language === "ar" ? "الحالة" : "Status",
      cell: row => <StatusBadge tone={inboundPostingStatusTone[row.status] ?? "neutral"}>{inboundPostingStatusLabel[row.status]?.[language] ?? row.status}</StatusBadge>,
    },
    {
      key: "created",
      header: language === "ar" ? "الإنشاء" : "Created",
      cell: row => <span className="text-xs">{row.created_at ? formatDateTime(row.created_at) : "-"}</span>,
    },
    {
      key: "posted",
      header: language === "ar" ? "ترحيل" : "Posted",
      cell: row => <span className="text-xs">{row.posted_at ? formatDateTime(row.posted_at) : "-"}</span>,
    },
    {
      key: "actions",
      header: language === "ar" ? "الإجراء" : "Action",
      align: "end",
      cell: row => (
        <div className="flex justify-end gap-2" onClick={e => e.stopPropagation()}>
          <Button size="sm" variant="outline" onClick={() => openDetail(row.id)}>
            <Eye className="h-3.5 w-3.5" />
            {language === "ar" ? "معاينة" : "Preview"}
          </Button>
        </div>
      ),
    },
  ]

  const ready = useMemo(() => items.filter(i => i.status === "approved").length, [items])
  const posted = useMemo(() => items.filter(i => i.status === "posted").length, [items])
  const closed = useMemo(() => items.filter(i => i.status === "closed").length, [items])

  const setFilter = (key: keyof InboundPostingFilters, value: string) => {
    setPage(1)
    setFilters(current => ({ ...current, [key]: value || undefined }))
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title={language === "ar" ? "أمر التوريد المخزني" : "Stock Supply Order"}
        description={language === "ar" ? "مراجعة واعتماد وترحيل الاستلامات إلى المخزون." : "Review, approve, and post receiving orders into inventory."}
        breadcrumbs={[
          { label: language === "ar" ? "المخزون واللوجستيات" : "Inventory & Logistics", href: "#" },
          { label: language === "ar" ? "أمر التوريد المخزني" : "Stock Supply Order" },
        ]}
        actions={
          <Button variant="outline" onClick={refresh} disabled={isLoading}>
            <RefreshCw className="h-4 w-4" />
          </Button>
        }
      />

      <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
        <KpiCard label={language === "ar" ? "إجمالي" : "Total"} value={String(total)} icon={FileCheck2} tone="gold" accent />
        <KpiCard label={language === "ar" ? "جاهز للترحيل" : "Ready to post"} value={String(ready)} icon={Clock3} tone="warning" />
        <KpiCard label={language === "ar" ? "مرحل" : "Posted"} value={String(posted)} icon={CheckCircle2} tone="success" />
        <KpiCard label={language === "ar" ? "مغلق" : "Closed"} value={String(closed)} icon={CheckCircle2} tone="info" />
      </div>

      <SectionCard title={language === "ar" ? "البحث والتصفية" : "Search and filters"}>
        <div className="grid gap-3 md:grid-cols-3 xl:grid-cols-4">
          <label className="relative xl:col-span-2">
            <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
            <input
              className="w-full rounded-lg border border-border bg-background py-2.5 pl-9 pr-3 text-sm"
              placeholder={language === "ar" ? "رقم الاستلام" : "Receiving number"}
              value={filters.search ?? ""}
              onChange={e => setFilter("search", e.target.value)}
            />
          </label>
          <select className="rounded-lg border border-border bg-background px-3 text-sm" value={filters.status_filter ?? ""} onChange={e => setFilter("status_filter", e.target.value)}>
            <option value="">{language === "ar" ? "كل الحالات" : "All statuses"}</option>
            {Object.entries(inboundPostingStatusLabel).map(([value, label]) => <option key={value} value={value}>{label[language]}</option>)}
          </select>
        </div>
      </SectionCard>

      <SectionCard title={language === "ar" ? "قائمة الترحيلات" : "Postings"} padded={false}>
        {error && <div className="m-4 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-700">{error}</div>}
        {isLoading ? (
          <div className="flex h-52 items-center justify-center">
            <div className="h-8 w-8 animate-spin rounded-full border-4 border-gold-500 border-t-transparent" />
          </div>
        ) : (
          <DataTable
            columns={columns}
            data={items}
            rowKey={row => row.id}
            onRowClick={row => openDetail(row.id)}
            ariaLabel="Stock supply orders"
            empty={<div className="text-center text-sm text-muted-foreground">{language === "ar" ? "لا توجد ترحيلات." : "No postings."}</div>}
          />
        )}
        <Pagination currentPage={page} totalPages={pages} onPageChange={setPage} />
      </SectionCard>
    </div>
  )
}
