'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 { Archive, Shield, PlusCircle, Server, Activity } from "lucide-react"
import { formatDateTime, formatNumber } from "@/lib/format"
import { useVaults, type VaultCreateDTO } from "@/hooks/useVaults"
import type { VaultDTO } from "@/types"
import { useBranches } from "@/hooks/useBranches"
import { Modal } from "@/components/ui/modal"
import { InputField, SelectField } 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.vaults.page.text_1'), tone: "success" },
  inactive: { label: i18n.t('app.admin.warehouse.vaults.page.text_2'), tone: "danger" },
  maintenance: { label: i18n.t('app.admin.warehouse.vaults.page.text_3'), tone: "warning" },
}

const typeMap: Record<string, string> = {
  main: i18n.t('app.admin.warehouse.vaults.page.text_4'),
  in_transit: i18n.t('app.admin.warehouse.vaults.page.text_5'),
  platform_bars: i18n.t('app.admin.warehouse.vaults.page.text_6'),
  customer_bars: i18n.t('app.admin.warehouse.vaults.page.text_7'),
  inspection: i18n.t('app.admin.warehouse.vaults.page.text_8'),
  scrap: i18n.t('app.admin.warehouse.vaults.page.text_9'),
  fractional_pool: i18n.t('app.admin.warehouse.vaults.page.text_10'),
}

export default function VaultsPage() {
  const { items: vaults, isLoading, fetchItems, createItem } = useVaults()
  const { items: branches, fetchItems: fetchBranches } = useBranches()
  
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [formData, setFormData] = useState<VaultCreateDTO>({
    code: "",
    name: "",
    vault_type: "main",
    security_level: "standard",
    allow_bars: true,
    allow_fractional: false,
    allow_delivery: false,
    is_staging: false,
  })

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

  const totalVaults = vaults.length
  const activeVaults = useMemo(() => vaults.filter(v => v.status === 'active').length, [vaults])
  
  // High security vaults
  const highSecurityVaults = useMemo(() => vaults.filter(v => 
    v.security_level === 'high' || v.security_level === 'maximum'
  ).length, [vaults])

  const columns: Column<VaultDTO>[] = [
    {
      key: "code",
      header: i18n.t('app.admin.warehouse.vaults.page.text_11'),
      cell: (row) => (
        <div className="flex items-center gap-2">
          <Archive className="h-4 w-4 text-muted-foreground" />
          <span className="font-mono text-sm font-medium">{String(row.code)}</span>
        </div>
      ),
    },
    {
      key: "name",
      header: i18n.t('app.admin.warehouse.vaults.page.text_12'),
      cell: (row) => <span className="font-medium">{String(row.name)}</span>,
    },
    {
      key: "vault_type",
      header: i18n.t('app.admin.warehouse.vaults.page.text_13'),
      cell: (row) => {
        const t = String(row.vault_type).toLowerCase()
        return <span className="text-sm">{typeMap[t] || String(row.vault_type)}</span>
      },
    },
    {
      key: "security_level",
      header: i18n.t('app.admin.warehouse.vaults.page.text_14'),
      cell: (row) => {
        const level = String(row.security_level).toLowerCase()
        let tone: StatusTone = "neutral"
        if (level === 'high' || level === 'maximum') tone = "success"
        if (level === 'medium') tone = "warning"
        if (level === 'low') tone = "danger"
        
        return (
          <div className="flex items-center gap-1.5">
            <Shield className={`h-3 w-3 ${tone === 'success' ? 'text-emerald-500' : 'text-muted-foreground'}`} />
            <span className="text-xs uppercase">{level}</span>
          </div>
        )
      },
    },
    {
      key: "capacity",
      header: i18n.t('app.admin.warehouse.vaults.page.text_15'),
      cell: (row) => (
        <div className="flex flex-col gap-1 w-32">
          <div className="flex justify-between text-xs">
            <span>{formatNumber(Number(row.current_hold_grams || 0))}</span>
            <span className="text-muted-foreground">/ {formatNumber(Number(row.max_capacity_grams || 0))}</span>
          </div>
          {Number(row.max_capacity_grams) > 0 && (
            <div className="h-1.5 w-full bg-secondary rounded-full overflow-hidden">
              <div 
                className={`h-full ${(Number(row.current_hold_grams) / Number(row.max_capacity_grams)) > 0.9 ? 'bg-destructive' : 'bg-primary'}`} 
                style={{ width: `${Math.min(100, (Number(row.current_hold_grams || 0) / Number(row.max_capacity_grams)) * 100)}%` }}
              />
            </div>
          )}
        </div>
      ),
    },
    {
      key: "status",
      header: i18n.t('app.admin.warehouse.vaults.page.text_16'),
      cell: (row) => {
        const s = statusMap[String(row.status).toLowerCase()] || { label: String(row.status), tone: "neutral" }
        return <StatusBadge tone={s.tone}>{s.label}</StatusBadge>
      },
    },
  ]

  return (
    <div className="flex flex-col gap-6">
      <PageHeader 
        title={i18n.t('app.admin.warehouse.vaults.page.text_17')} 
        description={i18n.t('app.admin.warehouse.vaults.page.text_18')}
        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.vaults.page.text_44')}</button>
        }
      />

      <div className="grid gap-4 md:grid-cols-3">
        <KpiCard
          title={i18n.t('app.admin.warehouse.vaults.page.text_19')}
          value={totalVaults}
          icon={Server}
          trend={{ value: 0, label: i18n.t('app.admin.warehouse.vaults.page.text_20'), isPositive: true }}
        />
        <KpiCard
          title={i18n.t('app.admin.warehouse.vaults.page.text_21')}
          value={activeVaults}
          icon={Activity}
          trend={{ value: 0, label: i18n.t('app.admin.warehouse.vaults.page.text_22'), isPositive: true }}
        />
        <KpiCard
          title={i18n.t('app.admin.warehouse.vaults.page.text_23')}
          value={highSecurityVaults}
          icon={Shield}
          trend={{ value: 0, label: i18n.t('app.admin.warehouse.vaults.page.text_24'), isPositive: true }}
        />
      </div>

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

      <Modal
        open={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        title={i18n.t('app.admin.warehouse.vaults.page.text_26')}
        description={i18n.t('app.admin.warehouse.vaults.page.text_27')}
        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.vaults.page.text_28'))
              setIsModalOpen(false)
              setFormData({
                code: "",
                name: "",
                vault_type: "main",
                security_level: "standard",
                allow_bars: true,
                allow_fractional: false,
                allow_delivery: false,
                is_staging: false,
              })
            }
          }}
        >
          <div className="grid grid-cols-2 gap-4">
            <InputField
              id="code"
              name="code"
              label={i18n.t('app.admin.warehouse.vaults.page.text_29')}
              required
              value={formData.code}
              onChange={(e) => setFormData(p => ({ ...p, code: e.target.value }))}
              placeholder={i18n.t('app.admin.warehouse.vaults.page.text_30')}
            />
            <InputField
              id="name"
              name="name"
              label={i18n.t('app.admin.warehouse.vaults.page.text_31')}
              required
              value={formData.name}
              onChange={(e) => setFormData(p => ({ ...p, name: e.target.value }))}
              placeholder={i18n.t('app.admin.warehouse.vaults.page.text_32')}
            />
          </div>

          <SelectField
            id="branch_id"
            name="branch_id"
            label={i18n.t('app.admin.warehouse.vaults.page.text_33')}
            value={formData.branch_id || ""}
            onChange={(e) => setFormData(p => ({ ...p, branch_id: e.target.value || undefined }))}
            options={branches.map(b => ({ value: b.id, label: b.name_ar }))}
            placeholder={i18n.t('app.admin.warehouse.vaults.page.text_34')}
          />

          <div className="grid grid-cols-2 gap-4">
            <SelectField
              id="vault_type"
              name="vault_type"
              label={i18n.t('app.admin.warehouse.vaults.page.text_35')}
              required
              value={formData.vault_type}
              onChange={(e) => setFormData(p => ({ ...p, vault_type: e.target.value }))}
              options={Object.entries(typeMap).map(([val, label]) => ({ value: val, label }))}
            />
            <SelectField
              id="security_level"
              name="security_level"
              label={i18n.t('app.admin.warehouse.vaults.page.text_36')}
              required
              value={formData.security_level}
              onChange={(e) => setFormData(p => ({ ...p, security_level: e.target.value }))}
              options={[
                { value: "standard", label: i18n.t('app.admin.warehouse.vaults.page.text_37') },
                { value: "high", label: i18n.t('app.admin.warehouse.vaults.page.text_38') },
                { value: "maximum", label: i18n.t('app.admin.warehouse.vaults.page.text_39') },
              ]}
            />
          </div>

          <InputField
            id="max_capacity_grams"
            name="max_capacity_grams"
            label={i18n.t('app.admin.warehouse.vaults.page.text_40')}
            type="number"
            min="0"
            step="0.01"
            value={formData.max_capacity_grams || ""}
            onChange={(e) => setFormData(p => ({ ...p, max_capacity_grams: e.target.value ? parseFloat(e.target.value) : undefined }))}
            placeholder={i18n.t('app.admin.warehouse.vaults.page.text_41')}
          />

          <div className="flex flex-col gap-3 py-2 border-t border-border mt-2 pt-4">
            <h4 className="text-sm font-semibold mb-1">{i18n.t('app.admin.warehouse.vaults.page.text_45')}</h4>
            <div className="grid grid-cols-2 gap-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.allow_bars}
                  onChange={(e) => setFormData(p => ({ ...p, allow_bars: e.target.checked }))}
                />
                <span className="text-sm">{i18n.t('app.admin.warehouse.vaults.page.text_46')}</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.allow_fractional}
                  onChange={(e) => setFormData(p => ({ ...p, allow_fractional: e.target.checked }))}
                />
                <span className="text-sm">{i18n.t('app.admin.warehouse.vaults.page.text_47')}</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.allow_delivery}
                  onChange={(e) => setFormData(p => ({ ...p, allow_delivery: e.target.checked }))}
                />
                <span className="text-sm">{i18n.t('app.admin.warehouse.vaults.page.text_48')}</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_staging}
                  onChange={(e) => setFormData(p => ({ ...p, is_staging: e.target.checked }))}
                />
                <span className="text-sm">{i18n.t('app.admin.warehouse.vaults.page.text_49')}</span>
              </label>
            </div>
          </div>

          <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.vaults.page.text_50')}</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.vaults.page.text_42') : i18n.t('app.admin.warehouse.vaults.page.text_43')}
            </button>
          </div>
        </form>
      </Modal>
    </div>
  )
}
