"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import {} from "lucide-react"

import { stockCountsApi } from "@/lib/api/stock-counts"
import { warehousesApi } from "@/lib/api/warehouses"
import { itemsApi } from "@/lib/api/items"
import { errorMessage } from "@/lib/error-map"
import { cn } from "@/lib/utils"
import { CountType } from "@/types/stock"
import { ItemListItem, Warehouse } from "@/types/master-data"

import { Button, buttonVariants } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { Checkbox } from "@/components/ui/checkbox"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton"
import { toast } from "@/components/ui/toast"

export default function NewCountPage() {
  const router = useRouter()

  const [warehouses, setWarehouses] = useState<Warehouse[] | null>(null)
  const [items, setItems] = useState<ItemListItem[] | null>(null)
  const [loadError, setLoadError] = useState<string | null>(null)

  const [warehouseId, setWarehouseId] = useState<number | null>(null)
  const [countType, setCountType] = useState<CountType>("Cycle")
  const [selectedItemIds, setSelectedItemIds] = useState<Set<number>>(new Set())

  const [submitError, setSubmitError] = useState<string | null>(null)
  const [submitting, setSubmitting] = useState(false)

  useEffect(() => {
    Promise.all([warehousesApi.list(), itemsApi.list({ pageSize: 200, status: "Active" })])
      .then(([wh, it]) => {
        setWarehouses(wh.items)
        setItems(it.items)
      })
      .catch((err) => setLoadError(errorMessage(err)))
  }, [])

  function toggleItem(itemId: number) {
    setSelectedItemIds((prev) => {
      const next = new Set(prev)
      if (next.has(itemId)) next.delete(itemId)
      else next.add(itemId)
      return next
    })
  }

  async function handleSubmit() {
    setSubmitError(null)

    if (!warehouseId) {
      setSubmitError("Select a warehouse.")
      return
    }
    if (selectedItemIds.size === 0) {
      setSubmitError("Select at least one item to count.")
      return
    }

    setSubmitting(true)
    try {
      const count = await stockCountsApi.create({ warehouseId, countType, itemIds: [...selectedItemIds] })
      toast.success("Count created", `${count.docNo} — system quantities snapshotted.`)
      router.push(`/dashboard/stock/counts/${count.countId}`)
    } catch (err) {
      setSubmitError(errorMessage(err))
      toast.error("Could not create count", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  const loading = !warehouses || !items

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-3">
        <div>
          <h1 className="text-2xl font-bold text-foreground">New Count</h1>
          <p className="text-base text-muted-foreground">System quantities are snapshotted immediately; enter counted quantities next.</p>
        </div>
      </div>

      {loadError && (
        <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-base text-destructive">{loadError}</div>
      )}

      {loading && !loadError && <Skeleton className="h-12 w-full" />}

      {!loading && (
        <>
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <div className="flex flex-col gap-2">
              <Label className="text-base">Warehouse</Label>
              <Select<number | null> value={warehouseId} onValueChange={(v) => setWarehouseId(v)}>
                <SelectTrigger className="h-12! w-full text-base">
                  <SelectValue placeholder="Select warehouse" />
                </SelectTrigger>
                <SelectContent>
                  {(warehouses ?? []).map((w) => (
                    <SelectItem key={w.warehouseId} value={w.warehouseId} className="text-base">
                      {w.code} — {w.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="flex flex-col gap-2">
              <Label className="text-base">Count type</Label>
              <Select<CountType> value={countType} onValueChange={(v) => setCountType(v ?? "Cycle")}>
                <SelectTrigger className="h-12! w-full text-base">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="Cycle" className="text-base">Cycle (partial, scheduled)</SelectItem>
                  <SelectItem value="Full" className="text-base">Full physical count</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="flex flex-col gap-3">
            <Label className="text-base">Items to count</Label>
            <div className="flex flex-col gap-1 rounded-xl border p-3">
              {(items ?? []).map((item) => (
                <label key={item.itemId} className="flex items-center gap-3 rounded-lg px-3 py-2.5 hover:bg-muted/50">
                  <Checkbox checked={selectedItemIds.has(item.itemId)} onCheckedChange={() => toggleItem(item.itemId)} />
                  <span className="text-base font-medium">{item.sku}</span>
                  <span className="text-sm text-muted-foreground">{item.name}</span>
                </label>
              ))}
            </div>
          </div>

          {submitError && (
            <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-base text-destructive">{submitError}</div>
          )}

          <div className="flex justify-end gap-3">
            <Link href="/dashboard/stock/counts" className={cn(buttonVariants({ variant: "outline", size: "lg" }))}>
              Cancel
            </Link>
            <Button size="lg" type="button" onClick={handleSubmit} disabled={submitting}>
              {submitting ? "Creating…" : "Create Count"}
            </Button>
          </div>
        </>
      )}
    </div>
  )
}
