// 3-panel "Danh sách HĐ" — Panel 1 (list compact, click chọn) | Panel 2
// (detail content) | Panel 3 (workflow + lịch sử duyệt). Selected HĐ giữ qua
// URL `?id=` để bookmarkable + back/forward navigation work.
//
// Mobile fallback (< lg): hiển thị Panel 1 list, click row → fullpage
// /contracts/:id (giữ flow cũ, không cố nhồi 3 panel vào màn hình hẹp).
import { useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { FileText, Plus, Search } from 'lucide-react'
import { ContractDetailContent } from '@/components/contracts/ContractDetailContent'
import { WorkflowHistoryPanel } from '@/components/contracts/WorkflowHistoryPanel'
import { PipelineTreePanel } from '@/components/pipeline/PipelineTreePanel'
import { PhaseBadge } from '@/components/PhaseBadge'
import { SlaTimer } from '@/components/SlaTimer'
import { EmptyState } from '@/components/EmptyState'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { api } from '@/lib/api'
import { cn } from '@/lib/cn'
import type { Paged } from '@/types/master'
import type { ContractDetail, ContractListItem } from '@/types/contracts'
import { ContractTypeLabel } from '@/types/forms'

const fmtMoney = (v: number) => v.toLocaleString('vi-VN')

export function MyContractsPage() {
  const navigate = useNavigate()
  const [searchParams, setSearchParams] = useSearchParams()
  const typeFilter = searchParams.get('type') ? Number(searchParams.get('type')) : null
  const selectedId = searchParams.get('id')
  const search = searchParams.get('q') ?? ''
  // [S159-đợt5] leaf 'Đã duyệt' (?phase=9 — BE /contracts có sẵn param phase) và
  // 'Đã xóa' (?deleted=1 — endpoint /contracts/deleted mới, chỉ-xem).
  const phaseFilter = searchParams.get('phase') ? Number(searchParams.get('phase')) : null
  const showDeleted = searchParams.get('deleted') === '1'

  const list = useQuery({
    queryKey: ['my-contracts', typeFilter, phaseFilter, showDeleted],
    queryFn: async () =>
      (
        await api.get<Paged<ContractListItem>>(showDeleted ? '/contracts/deleted' : '/contracts', {
          params: {
            page: 1,
            pageSize: 100,
            ...(showDeleted && typeFilter != null ? { type: typeFilter } : {}),
            ...(!showDeleted && phaseFilter != null ? { phase: phaseFilter } : {}),
          },
        })
      ).data,
  })

  const detail = useQuery({
    queryKey: ['contract', selectedId],
    queryFn: async () => (await api.get<ContractDetail>(`/contracts/${selectedId}`)).data,
    enabled: !!selectedId,
  })

  const rows = useMemo(() => {
    let items = list.data?.items ?? []
    if (typeFilter != null) items = items.filter(c => c.type === typeFilter)
    if (search.trim()) {
      const q = search.toLowerCase()
      items = items.filter(c =>
        (c.maHopDong ?? '').toLowerCase().includes(q) ||
        (c.tenHopDong ?? '').toLowerCase().includes(q) ||
        (c.supplierName ?? '').toLowerCase().includes(q),
      )
    }
    return items
  }, [list.data, typeFilter, search])

  function selectContract(id: string) {
    // [S159-đợt5 FLAG-2 reviewer] Màn "Đã xóa" = CHỈ XEM DANH SÁCH (khuôn PE S155
    // `disabled={deletedView}`): detail endpoint KHÔNG IgnoreQueryFilters ⇒ HĐ đã xóa
    // 404 ⇒ desktop = 2 panel trắng, mobile = navigate sang trang 404. Chặn tại gốc.
    if (showDeleted) return
    // Desktop ≥ lg: cập nhật URL để render Panel 2/3 cạnh List.
    // Mobile: Panel 2/3 hidden → navigate fullpage /contracts/:id (UX khả dụng).
    if (typeof window !== 'undefined' && window.matchMedia('(min-width: 1024px)').matches) {
      const next = new URLSearchParams(searchParams)
      next.set('id', id)
      setSearchParams(next, { replace: false })
    } else {
      navigate(`/contracts/${id}`)
    }
  }

  function clearSelection() {
    const next = new URLSearchParams(searchParams)
    next.delete('id')
    setSearchParams(next, { replace: false })
  }

  function updateSearch(value: string) {
    const next = new URLSearchParams(searchParams)
    if (value) next.set('q', value)
    else next.delete('q')
    setSearchParams(next, { replace: true })
  }

  const typeLabel = typeFilter != null ? ContractTypeLabel[typeFilter] : null

  return (
    <div className="flex h-[calc(100vh-4rem)] flex-col">
      {/* Compact page header — chiếm ít chiều cao để 3 panel có max chỗ */}
      <header className="flex shrink-0 flex-wrap items-center justify-between gap-3 border-b border-slate-200 bg-white px-6 py-3">
        <div className="flex items-center gap-2">
          <FileText className="h-5 w-5 text-slate-500" />
          <h1 className="text-base font-semibold tracking-tight text-slate-900">
            HĐ của tôi {typeLabel && <span className="text-slate-500">· {typeLabel}</span>}
          </h1>
          <span className="ml-2 rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-medium text-slate-600">
            {rows.length}
          </span>
        </div>
        {showDeleted && (
          <span className="rounded-full bg-slate-100 px-2.5 py-1 text-[11px] font-semibold text-slate-600 ring-1 ring-inset ring-slate-300">
            Đã xóa — chỉ xem
          </span>
        )}
        {!showDeleted && phaseFilter === 9 && (
          <span className="rounded-full bg-teal-50 px-2.5 py-1 text-[11px] font-semibold text-teal-700 ring-1 ring-inset ring-teal-200">
            Đã phát hành
          </span>
        )}
        {!showDeleted && (
          <Button onClick={() => navigate(typeFilter ? `/contracts/new?type=${typeFilter}` : '/contracts/new')}>
            <Plus className="h-4 w-4" />
            Tạo HĐ mới
          </Button>
        )}
      </header>

      {/* 3-panel grid — flex-1 để fill phần còn lại của viewport */}
      <div className="grid flex-1 grid-cols-1 overflow-hidden lg:grid-cols-[320px_1fr_360px]">
        {/* Panel 1 — List */}
        <aside className="flex flex-col overflow-hidden border-r border-slate-200 bg-white">
          <div className="border-b border-slate-200 p-3">
            <div className="relative">
              <Search className="pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-slate-400" />
              <Input
                value={search}
                onChange={e => updateSearch(e.target.value)}
                placeholder="Tìm theo mã / tên / NCC…"
                className="pl-8"
              />
            </div>
          </div>
          <div className="flex-1 overflow-y-auto">
            {list.isLoading && (
              <div className="space-y-2 p-3">
                {Array.from({ length: 6 }).map((_, i) => (
                  <div key={i} className="h-16 animate-pulse rounded-md bg-slate-100" />
                ))}
              </div>
            )}
            {!list.isLoading && rows.length === 0 && (
              <div className="p-6">
                <EmptyState
                  icon={FileText}
                  title="Không có HĐ"
                  description={showDeleted ? 'Chưa có HĐ nào bị xóa.' : typeFilter != null ? 'Loại HĐ này chưa có dữ liệu.' : 'Tạo HĐ mới để bắt đầu.'}
                />
              </div>
            )}
            <ul className="divide-y divide-slate-100">
              {rows.map(c => (
                <li key={c.id}>
                  <button
                    onClick={() => selectContract(c.id)}
                    className={cn(
                      'block w-full px-3 py-2.5 text-left transition hover:bg-slate-50',
                      selectedId === c.id && 'bg-brand-50 ring-1 ring-inset ring-brand-200',
                    )}
                  >
                    <div className="flex items-start justify-between gap-2">
                      <div className="min-w-0 flex-1">
                        <div className="truncate text-[13px] font-medium text-slate-900">
                          {c.tenHopDong ?? '(chưa đặt tên)'}
                        </div>
                        <div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-slate-500">
                          <span className="font-mono">{c.maHopDong ?? '—'}</span>
                          <span>·</span>
                          <span className="truncate">{c.supplierName}</span>
                        </div>
                      </div>
                      <PhaseBadge phase={c.phase} className="shrink-0 text-[10px]" />
                    </div>
                    <div className="mt-1 flex items-center justify-between text-[11px] text-slate-500">
                      <span>{fmtMoney(c.giaTri)}</span>
                      <SlaTimer deadline={c.slaDeadline} createdAt={c.createdAt} />
                    </div>
                  </button>
                </li>
              ))}
            </ul>
          </div>
        </aside>

        {/* Panel 2 — Detail content */}
        <main className="hidden overflow-y-auto bg-slate-50 p-6 lg:block">
          {!selectedId && (
            <EmptyState
              icon={FileText}
              title="Chọn 1 HĐ ở danh sách bên trái"
              description="Chi tiết HĐ + thông tin / góp ý / file đính kèm sẽ hiển thị ở đây."
            />
          )}
          {selectedId && detail.isLoading && (
            <div className="text-sm text-slate-500">Đang tải HĐ…</div>
          )}
          {selectedId && detail.data && (
            <ContractDetailContent contract={detail.data} onBack={clearSelection} />
          )}
        </main>

        {/* Panel 3 — Workflow + history */}
        <aside className="hidden overflow-y-auto border-l border-slate-200 bg-white p-4 lg:block">
          {/* [S168 GĐ3-D — owner slot (63) chốt D] Chưa chọn HĐ ⇒ cây toàn trình (GĐ3)
              thế chỗ ô trống; chọn HĐ thì nhường chỗ cho quy trình duyệt. Trade-off D
              (cây rời panel khi chọn HĐ) — sub-implfe-gd3.md §1. */}
          {/* [gate F-1/F-2] Panel-3 TỰ CUỘN ⇒ thân cây `lg:max-h-none` giữ đúng 1 thanh cuộn;
              sticky/self-start của khuôn vô hiệu ở host display:block này — by-design. */}
          {!selectedId && <PipelineTreePanel currentStage={3} bodyMaxHClass="max-h-[28rem] lg:max-h-none" />}
          {selectedId && detail.data && <WorkflowHistoryPanel contract={detail.data} />}
        </aside>
      </div>

    </div>
  )
}
