'use client'

import { useEffect, useState, useMemo } from "react"
import { PageHeader } from "@/components/ui/page-header"
import { KpiCard } from "@/components/ui/kpi-card"
import { SectionCard } from "@/components/ui/section-card"
import { DataTable, type Column } from "@/components/ui/data-table"
import { StatusBadge, type StatusTone } from "@/components/ui/status-badge"
import { Building2, Store, PlusCircle, CheckCircle, XCircle } from "lucide-react"
import { formatDateTime } from "@/lib/format"
import { useBranches, type BranchCreateDTO } from "@/hooks/useBranches"
import type { BranchDTO } from "@/types"
import { Modal } from "@/components/ui/modal"
import { InputField } from "@/components/ui/FormFields"
import { toast } from "sonner"
import i18n from "@/lib/i18n";

const statusMap: Record<string, { label: string; tone: StatusTone }> = {
  active: { label: i18n.t('app.admin.warehouse.branches.page.text_1'), tone: "success" },
  inactive: { label: i18n.t('app.admin.warehouse.branches.page.text_2'), tone: "danger" },
  suspended: { label: i18n.t('app.admin.warehouse.branches.page.text_3'), tone: "warning" },
}

export default function BranchesPage() {
  const { items: branches, isLoading, fetchItems, createItem } = useBranches()
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [formData, setFormData] = useState<BranchCreateDTO>({
    code: "",
    name_ar: "",
    name_en: "",
    is_receiving_branch: false,
    is_delivery_branch: false,
    operating_hours: "",
    status: "active"
  })

  useEffect(() => {
    fetchItems()
  }, [fetchItems])

  const totalBranches = branches.length
  const activeBranches = useMemo(() => branches.filter(b => b.status === 'active').length, [branches])
  const deliveryBranches = useMemo(() => branches.filter(b => b.is_delivery_branch).length, [branches])

  const columns: Column<BranchDTO>[] = [
    {
      key: "code",
      header: i18n.t('app.admin.warehouse.branches.page.text_4'),
      cell: (row) => (
        <div className="flex items-center gap-2">
          <Store className="h-4 w-4 text-muted-foreground" />
          <span className="font-mono text-sm font-medium">{String(row.code)}</span>
        </div>
      ),
    },
    {
      key: "name_ar",
      header: i18n.t('app.admin.warehouse.branches.page.text_5'),
      cell: (row) => (
        <div className="flex flex-col">
          <span className="font-medium">{String(row.name_ar)}</span>
          {row.name_en && <span className="text-xs text-muted-foreground">{row.name_en}</span>}
        </div>
      ),
    },
    {
      key: "is_receiving_branch",
      header: i18n.t('app.admin.warehouse.branches.page.text_6'),
      cell: (row) => row.is_receiving_branch ? <CheckCircle className="h-4 w-4 text-emerald-500" /> : <XCircle className="h-4 w-4 text-muted-foreground" />
    },
    {
      key: "is_delivery_branch",
      header: i18n.t('app.admin.warehouse.branches.page.text_7'),
      cell: (row) => row.is_delivery_branch ? <CheckCircle className="h-4 w-4 text-emerald-500" /> : <XCircle className="h-4 w-4 text-muted-foreground" />
    },
    {
      key: "status",
      header: i18n.t('app.admin.warehouse.branches.page.text_8'),
      cell: (row) => {
        const s = statusMap[String(row.status).toLowerCase()] || { label: String(row.status), tone: "neutral" }
        return <StatusBadge tone={s.tone}>{s.label}</StatusBadge>
      },
    },
    {
      key: "created_at",
      header: i18n.t('app.admin.warehouse.branches.page.text_9'),
      cell: (row) => <span className="text-sm text-muted-foreground">{formatDateTime(String(row.created_at))}</span>,
    },
  ]

  return (
    <div className="flex flex-col gap-6">
      <PageHeader 
        title={i18n.t('app.admin.warehouse.branches.page.text_10')} 
        description={i18n.t('app.admin.warehouse.branches.page.text_11')}
        actions={
          <button 
            onClick={() => setIsModalOpen(true)}
            className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring gap-2"
          >
            <PlusCircle className="h-4 w-4" />
            {i18n.t('app.admin.warehouse.branches.page.text_32')}</button>
        }
      />

      <div className="grid gap-4 md:grid-cols-3">
        <KpiCard
          title={i18n.t('app.admin.warehouse.branches.page.text_12')}
          value={totalBranches}
          icon={Building2}
          trend={{ value: 0, label: i18n.t('app.admin.warehouse.branches.page.text_13'), isPositive: true }}
        />
        <KpiCard
          title={i18n.t('app.admin.warehouse.branches.page.text_14')}
          value={activeBranches}
          icon={CheckCircle}
          trend={{ value: 0, label: i18n.t('app.admin.warehouse.branches.page.text_15'), isPositive: true }}
        />
        <KpiCard
          title={i18n.t('app.admin.warehouse.branches.page.text_16')}
          value={deliveryBranches}
          icon={Store}
          trend={{ value: 0, label: i18n.t('app.admin.warehouse.branches.page.text_17'), isPositive: true }}
        />
      </div>

      <SectionCard title={i18n.t('app.admin.warehouse.branches.page.text_18')}>
        <DataTable
          columns={columns}
          data={branches}
          rowKey={(row) => row.id}
        />
      </SectionCard>

      <Modal
        open={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        title={i18n.t('app.admin.warehouse.branches.page.text_19')}
        description={i18n.t('app.admin.warehouse.branches.page.text_20')}
        size="md"
      >
        <form 
          className="space-y-4"
          onSubmit={async (e) => {
            e.preventDefault()
            setIsSubmitting(true)
            const success = await createItem(formData)
            setIsSubmitting(false)
            if (success) {
              toast.success(i18n.t('app.admin.warehouse.branches.page.text_21'))
              setIsModalOpen(false)
              setFormData({
                code: "",
                name_ar: "",
                name_en: "",
                is_receiving_branch: false,
                is_delivery_branch: false,
                operating_hours: "",
                status: "active"
              })
            }
          }}
        >
          <InputField
            id="code"
            name="code"
            label={i18n.t('app.admin.warehouse.branches.page.text_22')}
            required
            value={formData.code}
            onChange={(e) => setFormData(p => ({ ...p, code: e.target.value }))}
            placeholder={i18n.t('app.admin.warehouse.branches.page.text_23')}
          />
          <InputField
            id="name_ar"
            name="name_ar"
            label={i18n.t('app.admin.warehouse.branches.page.text_24')}
            required
            value={formData.name_ar}
            onChange={(e) => setFormData(p => ({ ...p, name_ar: e.target.value }))}
            placeholder={i18n.t('app.admin.warehouse.branches.page.text_25')}
          />
          <InputField
            id="name_en"
            name="name_en"
            label={i18n.t('app.admin.warehouse.branches.page.text_26')}
            value={formData.name_en || ""}
            onChange={(e) => setFormData(p => ({ ...p, name_en: e.target.value }))}
            placeholder={i18n.t('app.admin.warehouse.branches.page.text_27')}
          />
          <div className="flex flex-col gap-3 py-2">
            <label className="flex items-center gap-2 cursor-pointer">
              <input 
                type="checkbox" 
                className="rounded border-border text-primary focus:ring-primary w-4 h-4"
                checked={formData.is_receiving_branch}
                onChange={(e) => setFormData(p => ({ ...p, is_receiving_branch: e.target.checked }))}
              />
              <span className="text-sm">{i18n.t('app.admin.warehouse.branches.page.text_33')}</span>
            </label>
            <label className="flex items-center gap-2 cursor-pointer">
              <input 
                type="checkbox" 
                className="rounded border-border text-primary focus:ring-primary w-4 h-4"
                checked={formData.is_delivery_branch}
                onChange={(e) => setFormData(p => ({ ...p, is_delivery_branch: e.target.checked }))}
              />
              <span className="text-sm">{i18n.t('app.admin.warehouse.branches.page.text_34')}</span>
            </label>
          </div>
          <InputField
            id="operating_hours"
            name="operating_hours"
            label={i18n.t('app.admin.warehouse.branches.page.text_28')}
            value={formData.operating_hours || ""}
            onChange={(e) => setFormData(p => ({ ...p, operating_hours: e.target.value }))}
            placeholder={i18n.t('app.admin.warehouse.branches.page.text_29')}
          />
          <div className="flex justify-end gap-3 pt-4 border-t border-border mt-6">
            <button
              type="button"
              onClick={() => setIsModalOpen(false)}
              className="px-4 py-2 text-sm font-medium text-foreground bg-muted hover:bg-muted/80 rounded-md transition-colors"
            >
              {i18n.t('app.admin.warehouse.branches.page.text_35')}</button>
            <button
              type="submit"
              disabled={isSubmitting}
              className="px-4 py-2 text-sm font-medium text-primary-foreground bg-primary hover:bg-primary/90 rounded-md transition-colors disabled:opacity-50"
            >
              {isSubmitting ? i18n.t('app.admin.warehouse.branches.page.text_30') : i18n.t('app.admin.warehouse.branches.page.text_31')}
            </button>
          </div>
        </form>
      </Modal>
    </div>
  )
}
