'use client'

import { useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import { useRouter, useParams } from 'next/navigation'
import { useForm } from 'react-hook-form'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { ArrowLeft, Save, Plus } from 'lucide-react'
import { toast } from 'sonner'
import {
  api,
  type MeasurementBook,
  type PaginatedResponse,
  type Contract,
  type Project,
  type Site,
} from '@/lib/api'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Select } from '@/components/ui/Select'
import { Card } from '@/components/ui/Card'
import { Badge } from '@/components/ui/Badge'

type FormValues = {
  contract_id: string
  project_id: string
  site_id: string
  mb_number: string
  period_start: string
  period_end: string
}

export function MbFormPage() {
  const { t } = useTranslation()
  const params = useParams()
  const id = params?.id as string | undefined
  const isEdit = Boolean(id)
  const router = useRouter()
  const queryClient = useQueryClient()
  const [boqItemId, setBoqItemId] = useState('')
  const [itemType, setItemType] = useState('area')
  const [rowQty, setRowQty] = useState('1')
  const [rowLength, setRowLength] = useState('')
  const [rowWidth, setRowWidth] = useState('')
  const [rowHeight, setRowHeight] = useState('')
  const [activeGroupId, setActiveGroupId] = useState<number | null>(null)

  const { register, handleSubmit, reset, watch, setValue } = useForm<FormValues>({
    defaultValues: {
      contract_id: '',
      project_id: '',
      site_id: '',
      mb_number: '',
      period_start: '',
      period_end: '',
    },
  })

  const contractId = watch('contract_id')
  const projectId = watch('project_id')

  const { data: mbData, refetch } = useQuery({
    queryKey: ['measurement-book', id],
    queryFn: () => api.get<{ data: MeasurementBook }>(`/measurement-books/${id}`),
    enabled: isEdit,
  })

  const { data: contractsData } = useQuery({
    queryKey: ['contracts-options'],
    queryFn: () =>
      api.get<PaginatedResponse<Contract>>('/contracts', { params: { per_page: 200 } }),
  })

  const { data: projectsData } = useQuery({
    queryKey: ['projects-options'],
    queryFn: () => api.get<PaginatedResponse<Project>>('/projects', { params: { per_page: 200 } }),
  })

  const { data: sitesData } = useQuery({
    queryKey: ['sites-options', projectId],
    queryFn: () =>
      api.get<PaginatedResponse<Site>>('/sites', {
        params: { project_id: projectId || undefined, per_page: 200 },
      }),
    enabled: Boolean(projectId),
  })

  const { data: contractDetail } = useQuery({
    queryKey: ['contract-detail', contractId],
    queryFn: () => api.get<{ data: Contract }>(`/contracts/${contractId}`),
    enabled: Boolean(contractId),
  })

  useEffect(() => {
    const m = mbData?.data?.data
    if (!m) return
    reset({
      contract_id: String(m.contract_id),
      project_id: String(m.project_id),
      site_id: String(m.site_id),
      mb_number: m.mb_number,
      period_start: m.period_start?.slice(0, 10) ?? '',
      period_end: m.period_end?.slice(0, 10) ?? '',
    })
  }, [mbData, reset])

  useEffect(() => {
    const c = (contractsData?.data.data ?? []).find((x) => String(x.id) === contractId)
    if (c?.project_id) setValue('project_id', String(c.project_id))
  }, [contractId, contractsData, setValue])

  const mutation = useMutation({
    mutationFn: (payload: Record<string, unknown>) =>
      isEdit
        ? api.put(`/measurement-books/${id}`, payload)
        : api.post('/measurement-books', payload),
    onSuccess: (res) => {
      toast.success(isEdit ? t('mb.messages.updated') : t('mb.messages.created'))
      queryClient.invalidateQueries({ queryKey: ['measurement-books'] })
      const newId = (res.data as { data?: { id?: number } })?.data?.id
      if (!isEdit && newId) router.push(`/measurement-books/${newId}/edit`)
      else router.push('/measurement-books')
    },
    onError: (err: { response?: { data?: { message?: string } } }) => {
      toast.error(err?.response?.data?.message || t('common.somethingWentWrong'))
    },
  })

  const transition = useMutation({
    mutationFn: (action: string) =>
      api.post(`/measurement-books/${id}/${action}`, action === 'reject' ? { reason: 'Rejected' } : {}),
    onSuccess: () => {
      toast.success(t('mb.messages.statusUpdated'))
      refetch()
      queryClient.invalidateQueries({ queryKey: ['measurement-books'] })
    },
    onError: (err: { response?: { data?: { message?: string } } }) => {
      toast.error(err?.response?.data?.message || t('common.somethingWentWrong'))
    },
  })

  const addGroup = useMutation({
    mutationFn: () =>
      api.post(`/measurement-books/${id}/item-groups`, {
        boq_item_id: Number(boqItemId),
        item_type: itemType,
      }),
    onSuccess: () => {
      toast.success(t('mb.messages.groupAdded'))
      setBoqItemId('')
      refetch()
    },
    onError: () => toast.error(t('common.somethingWentWrong')),
  })

  const addRow = useMutation({
    mutationFn: (gid: number) =>
      api.post(`/measurement-books/item-groups/${gid}/rows`, {
        quantity: Number(rowQty) || 0,
        length: rowLength === '' ? null : Number(rowLength),
        width: rowWidth === '' ? null : Number(rowWidth),
        height: rowHeight === '' ? null : Number(rowHeight),
        multiplier: 1,
      }),
    onSuccess: () => {
      toast.success(t('mb.messages.rowAdded'))
      setActiveGroupId(null)
      refetch()
    },
    onError: () => toast.error(t('common.somethingWentWrong')),
  })

  const mb = mbData?.data?.data
  const isDraft = !isEdit || mb?.status === 'draft'

  const contractOptions = useMemo(
    () => [
      { value: '', label: t('mb.selectContract') },
      ...(contractsData?.data.data ?? []).map((c) => ({
        value: String(c.id),
        label: `${c.contract_number} — ${c.title}`,
      })),
    ],
    [contractsData, t],
  )

  const projectOptions = useMemo(
    () => [
      { value: '', label: t('mb.selectProject') },
      ...(projectsData?.data.data ?? []).map((p) => ({
        value: String(p.id),
        label: `${p.project_code} — ${p.name}`,
      })),
    ],
    [projectsData, t],
  )

  const siteOptions = useMemo(
    () => [
      { value: '', label: t('mb.selectSite') },
      ...(sitesData?.data.data ?? []).map((s) => ({
        value: String(s.id),
        label: `${s.site_code} — ${s.name}`,
      })),
    ],
    [sitesData, t],
  )

  const boqOptions = useMemo(
    () => [
      { value: '', label: t('mb.selectBoq') },
      ...(contractDetail?.data?.data?.boq_items ?? []).map((b) => ({
        value: String(b.id),
        label: `${b.item_code || b.id} — ${b.description}`,
      })),
    ],
    [contractDetail, t],
  )

  const onSubmit = (data: FormValues) => {
    mutation.mutate({
      contract_id: Number(data.contract_id),
      project_id: Number(data.project_id),
      site_id: Number(data.site_id),
      mb_number: data.mb_number || undefined,
      period_start: data.period_start || null,
      period_end: data.period_end || null,
    })
  }

  return (
    <div className="space-y-5">
      <div className="animate-fade-in-up flex flex-wrap items-center gap-3">
        <Link href="/measurement-books">
          <button
            type="button"
            className="premium-chip press-btn flex items-center gap-1.5 rounded-xl px-3 py-2 text-sm"
          >
            <ArrowLeft size={15} />
            {t('common.back')}
          </button>
        </Link>
        <h1 className="premium-heading text-2xl font-bold">
          {isEdit ? t('mb.edit') : t('mb.create')}
        </h1>
        {mb && <Badge variant="muted">{t(`mb.status.${mb.status}`, mb.status)}</Badge>}
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-5">
        <Card elevated>
          <div className="grid gap-4 sm:grid-cols-2">
            <div>
              <label className="mb-1.5 block text-xs font-medium text-[var(--text-muted)]">
                {t('mb.contract')} *
              </label>
              <Select
                {...register('contract_id', { required: true })}
                options={contractOptions}
                disabled={!isDraft || isEdit}
              />
            </div>
            <div>
              <label className="mb-1.5 block text-xs font-medium text-[var(--text-muted)]">
                {t('mb.mbNumber')}
              </label>
              <Input {...register('mb_number')} placeholder="Auto" disabled={!isDraft} />
            </div>
            <div>
              <label className="mb-1.5 block text-xs font-medium text-[var(--text-muted)]">
                {t('mb.project')} *
              </label>
              <Select
                {...register('project_id', { required: true })}
                options={projectOptions}
                disabled={!isDraft || isEdit}
              />
            </div>
            <div>
              <label className="mb-1.5 block text-xs font-medium text-[var(--text-muted)]">
                {t('mb.site')} *
              </label>
              <Select
                {...register('site_id', { required: true })}
                options={siteOptions}
                disabled={!isDraft}
              />
            </div>
            <div>
              <label className="mb-1.5 block text-xs font-medium text-[var(--text-muted)]">
                {t('mb.periodStart')}
              </label>
              <Input type="date" {...register('period_start')} disabled={!isDraft} />
            </div>
            <div>
              <label className="mb-1.5 block text-xs font-medium text-[var(--text-muted)]">
                {t('mb.periodEnd')}
              </label>
              <Input type="date" {...register('period_end')} disabled={!isDraft} />
            </div>
          </div>
          {isDraft && (
            <div className="mt-5 flex justify-end gap-3">
              <Button type="submit" disabled={mutation.isPending}>
                <Save size={15} />
                {mutation.isPending ? t('common.saving') : t('common.saveChanges')}
              </Button>
            </div>
          )}
        </Card>
      </form>

      {isEdit && mb && (
        <>
          <Card elevated>
            <div className="mb-3 flex flex-wrap gap-2">
              {mb.status === 'draft' && (
                <Button size="sm" onClick={() => transition.mutate('submit')}>
                  {t('mb.submit')}
                </Button>
              )}
              {mb.status === 'submitted' && (
                <>
                  <Button size="sm" onClick={() => transition.mutate('verify')}>
                    {t('mb.verify')}
                  </Button>
                  <Button size="sm" variant="secondary" onClick={() => transition.mutate('reject')}>
                    {t('mb.reject')}
                  </Button>
                </>
              )}
              {mb.status === 'verified' && (
                <>
                  <Button size="sm" onClick={() => transition.mutate('approve')}>
                    {t('mb.approve')}
                  </Button>
                  <Button size="sm" variant="secondary" onClick={() => transition.mutate('reject')}>
                    {t('mb.reject')}
                  </Button>
                </>
              )}
            </div>

            <h3 className="mb-3 text-sm font-semibold">{t('mb.itemGroups')}</h3>
            {(mb.item_groups ?? []).map((g) => (
              <div
                key={g.id}
                className="mb-3 rounded-xl border border-[var(--premium-divider)] p-3"
              >
                <div className="mb-2 text-sm font-medium">
                  {g.boq_item?.description || `BoQ #${g.boq_item_id}`}{' '}
                  <span className="text-[var(--text-muted)]">({g.item_type})</span>
                </div>
                <div className="space-y-1 text-xs text-[var(--text-muted)]">
                  {(g.rows ?? []).map((r) => (
                    <div key={r.id}>
                      subtotal: {r.subtotal} (qty {r.quantity ?? '—'}, L×W×H{' '}
                      {r.length ?? '—'}×{r.width ?? '—'}×{r.height ?? '—'})
                    </div>
                  ))}
                </div>
                {isDraft && (
                  <div className="mt-2">
                    {activeGroupId === g.id ? (
                      <div className="flex flex-wrap gap-2">
                        <Input
                          className="w-20"
                          value={rowQty}
                          onChange={(e) => setRowQty(e.target.value)}
                          placeholder="Qty"
                        />
                        <Input
                          className="w-20"
                          value={rowLength}
                          onChange={(e) => setRowLength(e.target.value)}
                          placeholder="L"
                        />
                        <Input
                          className="w-20"
                          value={rowWidth}
                          onChange={(e) => setRowWidth(e.target.value)}
                          placeholder="W"
                        />
                        <Input
                          className="w-20"
                          value={rowHeight}
                          onChange={(e) => setRowHeight(e.target.value)}
                          placeholder="H"
                        />
                        <Button size="sm" onClick={() => addRow.mutate(g.id)}>
                          {t('common.save')}
                        </Button>
                      </div>
                    ) : (
                      <Button size="sm" variant="secondary" onClick={() => setActiveGroupId(g.id)}>
                        <Plus size={14} />
                        {t('mb.addRow')}
                      </Button>
                    )}
                  </div>
                )}
              </div>
            ))}

            {isDraft && (
              <div className="mt-3 flex flex-wrap gap-2">
                <Select
                  value={boqItemId}
                  onChange={(e) => setBoqItemId(e.target.value)}
                  options={boqOptions}
                />
                <Select
                  value={itemType}
                  onChange={(e) => setItemType(e.target.value)}
                  options={[
                    { value: 'area', label: 'Area' },
                    { value: 'volume', label: 'Volume' },
                    { value: 'steel', label: 'Steel' },
                    { value: 'custom', label: 'Custom' },
                  ]}
                />
                <Button
                  size="sm"
                  disabled={!boqItemId || addGroup.isPending}
                  onClick={() => addGroup.mutate()}
                >
                  <Plus size={14} />
                  {t('mb.addGroup')}
                </Button>
              </div>
            )}
          </Card>
        </>
      )}
    </div>
  )
}
