'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, MapPin, Plus } from 'lucide-react'
import { toast } from 'sonner'
import {
  api,
  type PaginatedResponse,
  type Project,
  type Employee,
  type Site,
  type SiteLocation,
} 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'

type SiteForm = {
  project_id: string
  name: string
  address?: string
  city?: string
  status: string
  site_manager_id?: string
  start_date?: string
  planned_end_date?: string
  progress?: string
  notes?: string
}

function toDateInput(value?: string | null) {
  if (!value) return ''
  return String(value).slice(0, 10)
}

function LocationTree({
  locations,
  onAddChild,
  onDelete,
}: {
  locations: SiteLocation[]
  onAddChild: (parentId: number) => void
  onDelete: (id: number) => void
}) {
  return (
    <ul className="space-y-1 text-sm">
      {locations.map((loc) => (
        <li key={loc.id} className="rounded-lg bg-[var(--premium-hover-bg)] px-3 py-2">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <div>
              <span className="font-medium">{loc.name}</span>
              <span className="ml-2 text-xs text-[var(--premium-muted-text)]">{loc.location_type}</span>
            </div>
            <div className="flex gap-2">
              <button
                type="button"
                className="text-xs font-semibold text-accent-600 dark:text-accent-400"
                onClick={() => onAddChild(loc.id)}
              >
                + child
              </button>
              <button
                type="button"
                className="text-xs font-semibold text-red-500"
                onClick={() => onDelete(loc.id)}
              >
                delete
              </button>
            </div>
          </div>
          {loc.children && loc.children.length > 0 && (
            <div className="mt-2 ml-3 border-l border-[var(--premium-border)] pl-3">
              <LocationTree locations={loc.children} onAddChild={onAddChild} onDelete={onDelete} />
            </div>
          )}
        </li>
      ))}
    </ul>
  )
}

export function SiteFormPage() {
  const { t } = useTranslation()
  const params = useParams()
  const id = params?.id as string | undefined
  const isEdit = Boolean(id)
  const router = useRouter()
  const queryClient = useQueryClient()
  const [locName, setLocName] = useState('')
  const [locType, setLocType] = useState('building')
  const [parentId, setParentId] = useState<number | null>(null)

  const statuses = useMemo(
    () =>
      (['draft', 'active', 'completed', 'disabled'] as const).map((value) => ({
        value,
        label: t(`sites.status.${value}`),
      })),
    [t],
  )

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

  const employees = useQuery({
    queryKey: ['employees-options'],
    queryFn: () =>
      api.get<PaginatedResponse<Employee>>('/employees', { params: { per_page: 100, status: 'active' } }),
  })

  const existing = useQuery({
    queryKey: ['site', id],
    queryFn: () => api.get<{ data: Site }>(`/sites/${id}`),
    enabled: isEdit,
  })

  const {
    register,
    handleSubmit,
    reset,
    formState: { isSubmitting },
  } = useForm<SiteForm>({
    defaultValues: { status: 'draft', progress: '0' },
  })

  useEffect(() => {
    const row = existing.data?.data.data
    if (!row) return
    reset({
      project_id: String(row.project_id),
      name: row.name,
      address: row.address ?? '',
      city: row.city ?? '',
      status: row.status,
      site_manager_id: row.site_manager_id ? String(row.site_manager_id) : '',
      start_date: toDateInput(row.start_date),
      planned_end_date: toDateInput(row.planned_end_date),
      progress: String(row.progress ?? 0),
      notes: row.notes ?? '',
    })
  }, [existing.data, reset])

  const save = useMutation({
    mutationFn: (data: SiteForm) => {
      const payload = {
        ...data,
        site_manager_id: data.site_manager_id || null,
        progress: Number(data.progress || 0),
        start_date: data.start_date || null,
        planned_end_date: data.planned_end_date || null,
      }
      return isEdit ? api.put(`/sites/${id}`, payload) : api.post('/sites', payload)
    },
    onSuccess: () => {
      toast.success(isEdit ? t('sites.messages.updated') : t('sites.messages.created'))
      queryClient.invalidateQueries({ queryKey: ['sites'] })
      router.push('/sites')
    },
    onError: () => toast.error(t('common.somethingWentWrong')),
  })

  const addLocation = useMutation({
    mutationFn: () =>
      api.post(`/sites/${id}/locations`, {
        name: locName,
        location_type: locType,
        parent_id: parentId,
      }),
    onSuccess: () => {
      toast.success(t('sites.messages.locationAdded'))
      setLocName('')
      setParentId(null)
      queryClient.invalidateQueries({ queryKey: ['site', id] })
    },
    onError: () => toast.error(t('common.somethingWentWrong')),
  })

  const removeLocation = useMutation({
    mutationFn: (locationId: number) => api.delete(`/site-locations/${locationId}`),
    onSuccess: () => {
      toast.success(t('sites.messages.locationDeleted', 'Location deleted'))
      queryClient.invalidateQueries({ queryKey: ['site', id] })
    },
    onError: () => toast.error(t('common.somethingWentWrong')),
  })

  const projectOptions = (projects.data?.data.data ?? []).map((p) => ({
    value: String(p.id),
    label: `${p.project_code} — ${p.name}`,
  }))

  const employeeOptions = [
    { value: '', label: t('sites.noManager') },
    ...(employees.data?.data.data ?? []).map((e) => ({
      value: String(e.id),
      label: e.full_name,
    })),
  ]

  const locationTypes = [
    { value: 'building', label: t('sites.locationTypes.building') },
    { value: 'floor', label: t('sites.locationTypes.floor') },
    { value: 'zone', label: t('sites.locationTypes.zone') },
    { value: 'element', label: t('sites.locationTypes.element') },
  ]

  return (
    <div className="mx-auto max-w-3xl space-y-5">
      <div className="flex items-center gap-3">
        <Link href="/sites">
          <Button variant="secondary" size="sm">
            <ArrowLeft size={14} />
            {t('common.back')}
          </Button>
        </Link>
        <h1 className="premium-heading text-2xl font-bold">
          {isEdit ? t('sites.edit') : t('sites.create')}
        </h1>
      </div>

      <Card elevated>
        <form className="space-y-5" onSubmit={handleSubmit((v) => save.mutate(v))}>
          <div className="mb-2 flex items-center gap-2 border-b border-[var(--premium-divider)] pb-3">
            <MapPin size={16} className="text-accent-500" />
            <h3 className="text-sm font-semibold">{t('sites.sections.details')}</h3>
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <Select
              label={t('sites.project')}
              options={[{ value: '', label: t('sites.selectProject') }, ...projectOptions]}
              {...register('project_id', { required: true })}
            />
            <Input label={t('sites.name')} required {...register('name', { required: true })} />
            <Input label={t('sites.city')} {...register('city')} />
            <Select label={t('common.status')} options={statuses} {...register('status')} />
            <Select
              label={t('sites.siteManager')}
              options={employeeOptions}
              {...register('site_manager_id')}
            />
            <Input
              label={t('sites.progress')}
              type="number"
              min={0}
              max={100}
              {...register('progress')}
            />
            <Input label={t('sites.startDate')} type="date" {...register('start_date')} />
            <Input label={t('sites.plannedEnd')} type="date" {...register('planned_end_date')} />
          </div>

          <Input label={t('sites.address')} {...register('address')} />
          <div>
            <label className="mb-1.5 block text-xs font-medium text-[var(--text-muted)]">
              {t('sites.notes')}
            </label>
            <textarea
              className="min-h-20 w-full rounded-xl border border-[var(--premium-border)] bg-[var(--premium-field-bg)] px-3 py-2 text-sm"
              {...register('notes')}
            />
          </div>

          <div className="flex justify-end gap-2">
            <Link href="/sites">
              <Button type="button" variant="secondary">
                {t('common.cancel')}
              </Button>
            </Link>
            <Button type="submit" disabled={isSubmitting || save.isPending}>
              <Save size={14} />
              {isSubmitting || save.isPending ? t('common.saving') : t('common.save')}
            </Button>
          </div>
        </form>
      </Card>

      {isEdit && (
        <Card title={t('sites.sections.locations')} elevated>
          <div className="mb-4 grid gap-3 sm:grid-cols-[1fr_160px_auto]">
            <Input
              placeholder={
                parentId
                  ? `${t('sites.locationName')} (child of #${parentId})`
                  : t('sites.locationName')
              }
              value={locName}
              onChange={(e) => setLocName(e.target.value)}
            />
            <Select
              value={locType}
              onChange={(e) => setLocType(e.target.value)}
              options={locationTypes}
            />
            <Button
              size="sm"
              disabled={!locName || addLocation.isPending}
              onClick={() => addLocation.mutate()}
            >
              <Plus size={14} />
              {t('sites.addLocation')}
            </Button>
          </div>
          {parentId && (
            <button
              type="button"
              className="mb-3 text-xs text-[var(--premium-muted-text)] underline"
              onClick={() => setParentId(null)}
            >
              Clear parent (add as root)
            </button>
          )}
          {existing.data?.data.data.locations?.length ? (
            <LocationTree
              locations={existing.data.data.data.locations}
              onAddChild={(pid) => {
                setParentId(pid)
                setLocType('floor')
              }}
              onDelete={(lid) => {
                if (window.confirm(t('common.confirmDelete'))) removeLocation.mutate(lid)
              }}
            />
          ) : (
            <p className="text-sm text-[var(--text-muted)]">{t('sites.noLocations')}</p>
          )}
        </Card>
      )}
    </div>
  )
}
