'use client';

import React, { useState, useCallback } from 'react';
import { useForm, useFieldArray } from 'react-hook-form';
import { toast } from 'sonner';
import { Package, Plus, Trash2, ScanLine, ChevronDown, Filter, Search, CheckCircle, Clock, ArrowUpDown, Eye, RotateCcw, Loader2, Boxes, UserCheck, Activity,  } from 'lucide-react';
import {
  technicians,
  deviceCatalog,
  dispatchRecords,
  formatDate,
  DispatchRecord,
} from '@/lib/mockData';
import StatusBadge from '@/components/ui/StatusBadge';
import DispatchChart from './DispatchChart';

interface DispatchFormValues {
  technicianId: string;
  deviceId: string;
  notes: string;
  units: { serialNumber: string }[];
}

const statusOptions = ['Semua', 'assigned', 'installed', 'returned', 'exchanged'] as const;

export default function ONTDispatchPage() {
  const [tableRecords, setTableRecords] = useState<DispatchRecord[]>(dispatchRecords);
  const [filterStatus, setFilterStatus] = useState<string>('Semua');
  const [filterTech, setFilterTech] = useState<string>('Semua');
  const [searchQuery, setSearchQuery] = useState('');
  const [sortField, setSortField] = useState<keyof DispatchRecord>('dispatchDate');
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc');
  const [submitting, setSubmitting] = useState(false);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  const {
    register,
    control,
    handleSubmit,
    reset,
    watch,
    formState: { errors },
  } = useForm<DispatchFormValues>({
    defaultValues: {
      technicianId: '',
      deviceId: '',
      notes: '',
      units: [{ serialNumber: '' }],
    },
  });

  const { fields, append, remove } = useFieldArray({ control, name: 'units' });
  const selectedDevice = watch('deviceId');
  const deviceInfo = deviceCatalog.find((d) => d.id === selectedDevice);

  const onSubmit = useCallback(
    async (data: DispatchFormValues) => {
      setSubmitting(true);
      // Backend integration point: POST /api/dispatch with data
      await new Promise((r) => setTimeout(r, 1200));

      const tech = technicians.find((t) => t.id === data.technicianId)!;
      const device = deviceCatalog.find((d) => d.id === data.deviceId)!;
      const now = new Date().toISOString();

      const newRecords: DispatchRecord[] = data.units
        .filter((u) => u.serialNumber.trim())
        .map((u, i) => ({
          id: `dsp-new-${Date.now()}-${i}`,
          serialNumber: u.serialNumber.trim().toUpperCase(),
          deviceModel: device.model,
          deviceBrand: device.brand,
          technicianId: tech.id,
          technicianName: tech.name,
          pop: tech.pop,
          dispatchDate: now,
          dispatchedBy: 'Admin Gudang',
          status: 'assigned' as const,
          installationId: null,
          notes: data.notes,
        }));

      setTableRecords((prev) => [...newRecords, ...prev]);
      reset({ technicianId: '', deviceId: '', notes: '', units: [{ serialNumber: '' }] });
      setSubmitting(false);
      toast.success(`${newRecords.length} unit ONT berhasil di-dispatch ke ${tech.name}`);
    },
    [reset]
  );

  // Stats
  const totalDispatched = tableRecords.filter((r) => r.status === 'assigned').length;
  const totalInstalled = tableRecords.filter((r) => r.status === 'installed').length;
  const todayDispatched = tableRecords.filter((r) => {
    const d = new Date(r.dispatchDate);
    const today = new Date();
    return d.getDate() === today.getDate() && d.getMonth() === today.getMonth();
  }).length;
  const totalReturned = tableRecords.filter((r) => r.status === 'returned' || r.status === 'exchanged').length;

  // Filter + sort
  const filtered = tableRecords
    .filter((r) => {
      const matchStatus = filterStatus === 'Semua' || r.status === filterStatus;
      const matchTech = filterTech === 'Semua' || r.technicianId === filterTech;
      const q = searchQuery.toLowerCase();
      const matchSearch =
        !q ||
        r.serialNumber.toLowerCase().includes(q) ||
        r.technicianName.toLowerCase().includes(q) ||
        r.deviceModel.toLowerCase().includes(q) ||
        r.pop.toLowerCase().includes(q);
      return matchStatus && matchTech && matchSearch;
    })
    .sort((a, b) => {
      const av = a[sortField] ?? '';
      const bv = b[sortField] ?? '';
      return sortDir === 'asc'
        ? String(av).localeCompare(String(bv))
        : String(bv).localeCompare(String(av));
    });

  const totalPages = Math.ceil(filtered.length / pageSize);
  const paginated = filtered.slice((page - 1) * pageSize, page * pageSize);

  const handleSort = (field: keyof DispatchRecord) => {
    if (sortField === field) setSortDir((d) => (d === 'asc' ? 'desc' : 'asc'));
    else { setSortField(field); setSortDir('asc'); }
  };

  const SortIcon = ({ field }: { field: keyof DispatchRecord }) => (
    <ArrowUpDown
      size={13}
      className={`ml-1 inline-block ${sortField === field ? 'text-primary' : 'text-muted-foreground'}`}
    />
  );

  return (
    <div className="flex flex-col h-full">
      {/* Page header */}
      <div className="px-6 py-5 border-b border-border bg-card">
        <div className="flex items-center justify-between flex-wrap gap-3">
          <div>
            <h1 className="text-xl font-bold text-foreground">Dispatch & Assignment ONT</h1>
            <p className="text-sm text-muted-foreground mt-0.5">
              Catat pengeluaran unit ONT dari gudang ke teknisi lapangan
            </p>
          </div>
          <div className="flex items-center gap-2 text-xs text-muted-foreground">
            <Activity size={13} />
            <span>Update terakhir: 01/09/2026 08:05</span>
          </div>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto px-6 py-5 space-y-5 max-w-screen-2xl mx-auto w-full">
        {/* KPI row */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="card-elevated p-4 flex items-start gap-3">
            <div className="w-9 h-9 rounded-lg bg-blue-100 flex items-center justify-center shrink-0">
              <UserCheck size={18} className="text-primary" />
            </div>
            <div>
              <p className="section-label">Di Teknisi</p>
              <p className="text-2xl font-bold tabular-nums text-foreground mt-0.5">{totalDispatched}</p>
              <p className="text-xs text-muted-foreground">unit belum dipasang</p>
            </div>
          </div>

          <div className="card-elevated p-4 flex items-start gap-3">
            <div className="w-9 h-9 rounded-lg bg-green-100 flex items-center justify-center shrink-0">
              <CheckCircle size={18} className="text-accent" />
            </div>
            <div>
              <p className="section-label">Terpasang</p>
              <p className="text-2xl font-bold tabular-nums text-foreground mt-0.5">{totalInstalled}</p>
              <p className="text-xs text-muted-foreground">unit sudah instalasi</p>
            </div>
          </div>

          <div className="card-elevated p-4 flex items-start gap-3 border-amber-200 bg-amber-50">
            <div className="w-9 h-9 rounded-lg bg-amber-100 flex items-center justify-center shrink-0">
              <Clock size={18} className="text-warning" />
            </div>
            <div>
              <p className="section-label" style={{ color: 'var(--warning)' }}>Dispatch Hari Ini</p>
              <p className="text-2xl font-bold tabular-nums text-foreground mt-0.5">{todayDispatched}</p>
              <p className="text-xs text-amber-600">unit keluar hari ini</p>
            </div>
          </div>

          <div className="card-elevated p-4 flex items-start gap-3">
            <div className="w-9 h-9 rounded-lg bg-slate-100 flex items-center justify-center shrink-0">
              <RotateCcw size={18} className="text-muted-foreground" />
            </div>
            <div>
              <p className="section-label">Dikembalikan</p>
              <p className="text-2xl font-bold tabular-nums text-foreground mt-0.5">{totalReturned}</p>
              <p className="text-xs text-muted-foreground">retur / tukar</p>
            </div>
          </div>
        </div>

        {/* Main content: form + chart */}
        <div className="grid grid-cols-1 xl:grid-cols-5 gap-5">
          {/* Dispatch form */}
          <div className="xl:col-span-2">
            <div className="card-elevated">
              <div className="px-5 py-4 border-b border-border">
                <h2 className="text-base font-semibold text-foreground flex items-center gap-2">
                  <Package size={17} className="text-primary" />
                  Catat Barang Keluar
                </h2>
                <p className="text-xs text-muted-foreground mt-0.5">Dispatch ONT ke teknisi (maks. 5 unit sekaligus)</p>
              </div>

              <form onSubmit={handleSubmit(onSubmit)} className="px-5 py-4 space-y-4">
                {/* Technician */}
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Teknisi Penerima <span className="text-destructive">*</span>
                  </label>
                  <div className="relative">
                    <select
                      {...register('technicianId', { required: 'Pilih teknisi terlebih dahulu' })}
                      className="input-base appearance-none pr-8"
                    >
                      <option value="">-- Pilih Teknisi --</option>
                      {technicians.map((t) => (
                        <option key={`tech-opt-${t.id}`} value={t.id}>
                          {t.name} — {t.pop}
                        </option>
                      ))}
                    </select>
                    <ChevronDown size={15} className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none" />
                  </div>
                  {errors.technicianId && (
                    <p className="text-xs text-destructive mt-1">{errors.technicianId.message}</p>
                  )}
                </div>

                {/* Device model */}
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Model Perangkat <span className="text-destructive">*</span>
                  </label>
                  <div className="relative">
                    <select
                      {...register('deviceId', { required: 'Pilih model perangkat' })}
                      className="input-base appearance-none pr-8"
                    >
                      <option value="">-- Pilih Model --</option>
                      {deviceCatalog
                        .filter((d) => d.type === 'ONT')
                        .map((d) => (
                          <option key={`dev-opt-${d.id}`} value={d.id}>
                            {d.brand} {d.model}
                          </option>
                        ))}
                    </select>
                    <ChevronDown size={15} className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none" />
                  </div>
                  {errors.deviceId && (
                    <p className="text-xs text-destructive mt-1">{errors.deviceId.message}</p>
                  )}
                  {deviceInfo && (
                    <p className="text-xs text-muted-foreground mt-1">
                      Tipe: {deviceInfo.type} · Harga: Rp {deviceInfo.priceIDR.toLocaleString('id-ID')}
                    </p>
                  )}
                </div>

                {/* Serial numbers */}
                <div>
                  <div className="flex items-center justify-between mb-1">
                    <label className="text-sm font-medium text-foreground">
                      Serial Number ONT <span className="text-destructive">*</span>
                    </label>
                    <span className="text-xs text-muted-foreground">{fields.length}/5 unit</span>
                  </div>
                  <p className="text-xs text-muted-foreground mb-2">
                    Scan barcode atau ketik SN secara manual
                  </p>

                  <div className="space-y-2">
                    {fields.map((field, index) => (
                      <div key={field.id} className="flex items-center gap-2">
                        <div className="flex-1 relative">
                          <input
                            {...register(`units.${index}.serialNumber`, {
                              required: index === 0 ? 'SN tidak boleh kosong' : false,
                            })}
                            placeholder={`SN Unit ${index + 1}`}
                            className="input-base pr-9 font-mono text-xs uppercase"
                          />
                          <button
                            type="button"
                            className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-primary transition-colors"
                            title="Scan barcode/QR"
                          >
                            <ScanLine size={15} />
                          </button>
                        </div>
                        {fields.length > 1 && (
                          <button
                            type="button"
                            onClick={() => remove(index)}
                            className="p-1.5 rounded text-muted-foreground hover:text-destructive hover:bg-red-50 transition-colors"
                          >
                            <Trash2 size={15} />
                          </button>
                        )}
                      </div>
                    ))}
                  </div>

                  {fields.length < 5 && (
                    <button
                      type="button"
                      onClick={() => append({ serialNumber: '' })}
                      className="mt-2 flex items-center gap-1.5 text-sm text-primary hover:text-blue-700 font-medium transition-colors"
                    >
                      <Plus size={15} />
                      Tambah Unit
                    </button>
                  )}

                  {errors.units?.[0]?.serialNumber && (
                    <p className="text-xs text-destructive mt-1">
                      {errors.units[0].serialNumber.message}
                    </p>
                  )}
                </div>

                {/* Notes */}
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">Catatan</label>
                  <textarea
                    {...register('notes')}
                    rows={2}
                    placeholder="Catatan tambahan (opsional)..."
                    className="input-base resize-none"
                  />
                </div>

                <button
                  type="submit"
                  disabled={submitting}
                  className="btn-primary w-full justify-center"
                >
                  {submitting ? (
                    <>
                      <Loader2 size={15} className="animate-spin" />
                      Menyimpan...
                    </>
                  ) : (
                    <>
                      <Package size={15} />
                      Catat Dispatch ONT
                    </>
                  )}
                </button>
              </form>
            </div>
          </div>

          {/* Chart */}
          <div className="xl:col-span-3">
            <DispatchChart />
          </div>
        </div>

        {/* Dispatch history table */}
        <div className="card-elevated">
          <div className="px-5 py-4 border-b border-border">
            <div className="flex flex-wrap items-center gap-3 justify-between">
              <h2 className="text-base font-semibold text-foreground flex items-center gap-2">
                <Boxes size={17} className="text-primary" />
                Riwayat Dispatch
                <span className="text-sm font-normal text-muted-foreground">
                  ({filtered.length} record)
                </span>
              </h2>

              <div className="flex flex-wrap items-center gap-2">
                {/* Search */}
                <div className="relative">
                  <Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground" />
                  <input
                    type="text"
                    placeholder="Cari SN, teknisi, model..."
                    value={searchQuery}
                    onChange={(e) => { setSearchQuery(e.target.value); setPage(1); }}
                    className="input-base pl-8 w-52 text-sm"
                  />
                </div>

                {/* Filter status */}
                <div className="relative">
                  <select
                    value={filterStatus}
                    onChange={(e) => { setFilterStatus(e.target.value); setPage(1); }}
                    className="input-base appearance-none pr-7 text-sm w-36"
                  >
                    {statusOptions.map((s) => (
                      <option key={`filter-status-${s}`} value={s}>
                        {s === 'Semua' ? 'Semua Status' : s === 'assigned' ? 'Di Teknisi' : s === 'installed' ? 'Terpasang' : s === 'returned' ? 'Dikembalikan' : 'Ditukar'}
                      </option>
                    ))}
                  </select>
                  <ChevronDown size={13} className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none" />
                </div>

                {/* Filter technician */}
                <div className="relative">
                  <select
                    value={filterTech}
                    onChange={(e) => { setFilterTech(e.target.value); setPage(1); }}
                    className="input-base appearance-none pr-7 text-sm w-44"
                  >
                    <option value="Semua">Semua Teknisi</option>
                    {technicians.map((t) => (
                      <option key={`filter-tech-${t.id}`} value={t.id}>{t.name}</option>
                    ))}
                  </select>
                  <ChevronDown size={13} className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none" />
                </div>
              </div>
            </div>
          </div>

          {/* Table */}
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-border bg-muted/40">
                  <th className="text-left px-4 py-3 text-xs font-semibold text-muted-foreground whitespace-nowrap">
                    <button onClick={() => handleSort('serialNumber')} className="flex items-center hover:text-foreground transition-colors">
                      Serial Number <SortIcon field="serialNumber" />
                    </button>
                  </th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-muted-foreground whitespace-nowrap">
                    <button onClick={() => handleSort('deviceModel')} className="flex items-center hover:text-foreground transition-colors">
                      Model <SortIcon field="deviceModel" />
                    </button>
                  </th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-muted-foreground whitespace-nowrap">
                    <button onClick={() => handleSort('technicianName')} className="flex items-center hover:text-foreground transition-colors">
                      Teknisi <SortIcon field="technicianName" />
                    </button>
                  </th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-muted-foreground whitespace-nowrap">POP</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-muted-foreground whitespace-nowrap">
                    <button onClick={() => handleSort('dispatchDate')} className="flex items-center hover:text-foreground transition-colors">
                      Tgl Dispatch <SortIcon field="dispatchDate" />
                    </button>
                  </th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-muted-foreground whitespace-nowrap">Oleh</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-muted-foreground whitespace-nowrap">Status</th>
                  <th className="text-left px-4 py-3 text-xs font-semibold text-muted-foreground whitespace-nowrap">Catatan</th>
                  <th className="text-right px-4 py-3 text-xs font-semibold text-muted-foreground whitespace-nowrap">Aksi</th>
                </tr>
              </thead>
              <tbody>
                {paginated.length === 0 ? (
                  <tr>
                    <td colSpan={9} className="px-4 py-12 text-center">
                      <div className="flex flex-col items-center gap-2">
                        <Boxes size={32} className="text-muted-foreground/40" />
                        <p className="text-sm font-medium text-muted-foreground">Tidak ada record dispatch ditemukan</p>
                        <p className="text-xs text-muted-foreground">Coba ubah filter atau kata kunci pencarian</p>
                      </div>
                    </td>
                  </tr>
                ) : (
                  paginated.map((record, i) => (
                    <tr
                      key={`dispatch-row-${record.id}`}
                      className={`border-b border-border hover:bg-muted/40 transition-colors ${i % 2 === 0 ? '' : 'bg-muted/20'}`}
                    >
                      <td className="px-4 py-3 font-mono text-xs font-medium text-foreground whitespace-nowrap">
                        {record.serialNumber}
                      </td>
                      <td className="px-4 py-3 whitespace-nowrap">
                        <div>
                          <p className="text-sm font-medium text-foreground">{record.deviceModel}</p>
                          <p className="text-xs text-muted-foreground">{record.deviceBrand}</p>
                        </div>
                      </td>
                      <td className="px-4 py-3 whitespace-nowrap">
                        <div className="flex items-center gap-2">
                          <div className="w-6 h-6 rounded-full bg-primary/10 flex items-center justify-center shrink-0">
                            <span className="text-xs font-bold text-primary">
                              {record.technicianName.split(' ').map((n) => n[0]).slice(0, 2).join('')}
                            </span>
                          </div>
                          <span className="text-sm text-foreground">{record.technicianName}</span>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-xs text-muted-foreground whitespace-nowrap">
                        {record.pop}
                      </td>
                      <td className="px-4 py-3 text-xs text-muted-foreground whitespace-nowrap tabular-nums">
                        {formatDate(record.dispatchDate)}
                      </td>
                      <td className="px-4 py-3 text-xs text-muted-foreground whitespace-nowrap">
                        {record.dispatchedBy}
                      </td>
                      <td className="px-4 py-3 whitespace-nowrap">
                        <StatusBadge
                          variant={record.status === 'assigned' ? 'assigned' : record.status === 'installed' ? 'installed' : record.status === 'returned' ? 'returned' : 'exchanged'}
                        />
                      </td>
                      <td className="px-4 py-3 text-xs text-muted-foreground max-w-[120px] truncate">
                        {record.notes || '—'}
                      </td>
                      <td className="px-4 py-3 text-right whitespace-nowrap">
                        <div className="flex items-center justify-end gap-1">
                          <button
                            className="p-1.5 rounded hover:bg-blue-50 text-muted-foreground hover:text-primary transition-colors group relative"
                            title="Lihat detail"
                          >
                            <Eye size={14} />
                          </button>
                          {record.status === 'assigned' && (
                            <button
                              className="p-1.5 rounded hover:bg-amber-50 text-muted-foreground hover:text-warning transition-colors"
                              title="Catat retur"
                              onClick={() => {
                                setTableRecords((prev) =>
                                  prev.map((r) => r.id === record.id ? { ...r, status: 'returned' as const } : r)
                                );
                                toast.success(`ONT ${record.serialNumber} dicatat sebagai retur`);
                              }}
                            >
                              <RotateCcw size={14} />
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          <div className="px-5 py-3 border-t border-border flex flex-wrap items-center justify-between gap-3">
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <span>Tampilkan</span>
              <select
                value={pageSize}
                onChange={(e) => { setPageSize(Number(e.target.value)); setPage(1); }}
                className="input-base w-16 text-sm py-1"
              >
                {[5, 10, 20, 50].map((s) => (
                  <option key={`pagesize-${s}`} value={s}>{s}</option>
                ))}
              </select>
              <span>dari {filtered.length} record</span>
            </div>

            <div className="flex items-center gap-1">
              <button
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={page === 1}
                className="px-2.5 py-1.5 text-sm rounded border border-border hover:bg-muted disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
              >
                ‹
              </button>
              {Array.from({ length: Math.min(totalPages, 5) }, (_, i) => {
                const p = i + 1;
                return (
                  <button
                    key={`page-btn-${p}`}
                    onClick={() => setPage(p)}
                    className={`px-2.5 py-1.5 text-sm rounded border transition-colors ${
                      page === p
                        ? 'bg-primary text-primary-foreground border-primary'
                        : 'border-border hover:bg-muted'
                    }`}
                  >
                    {p}
                  </button>
                );
              })}
              <button
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                disabled={page === totalPages || totalPages === 0}
                className="px-2.5 py-1.5 text-sm rounded border border-border hover:bg-muted disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
              >
                ›
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}