'use client'

import { useEffect } 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 } from 'lucide-react'
import { toast } from 'sonner'
import {
  api,
  type Inspection,
  type InspectionTemplate,
  type PaginatedResponse,
  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'

type FormValues = {
  project_id: string
  site_id: string
  template_id: string
  inspected_at: string
}

export function InspectionFormPage() {
  const { t } = useTranslation()
  const params = useParams()
  const id = params?.id as string | undefined
  const isEdit = Boolean(id)
  const router = useRouter()
  const queryClient = useQueryClient()

  const { register, handleSubmit, reset, watch } = useForm<FormValues>({
    defaultValues: {
      project_id: '',
      site_id: '',
      template_id: '',
      inspected_at: new Date().toISOString().slice(0, 16),
    },
  })

  const projectId = watch('project_id')

  const { data: inspectionData } = useQuery({
    queryKey: ['inspection', id],
    queryFn: () => api.get<{ data: Inspection }>(`/inspections/${id}`),
    enabled: isEdit,
  })

  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: templatesData } = useQuery({
    queryKey: ['inspection-templates'],
    queryFn: () =>
      api.get<PaginatedResponse<InspectionTemplate>>('/inspection-templates', {
        params: { per_page: 200 },
      }),
  })

  useEffect(() => {
    const row = inspectionData?.data?.data
    if (!row) return
    reset({
      project_id: String(row.project_id),
      site_id: String(row.site_id),
      template_id: row.template_id ? String(row.template_id) : '',
      inspected_at: row.inspected_at?.slice(0, 16) ?? '',
    })
  }, [inspectionData, reset])

  const save = useMutation({
    mutationFn: (payload: Record<string, unknown>) =>
      isEdit ? api.put(`/inspections/${id}`, payload) : api.post('/inspections', payload),
    onSuccess: (res) => {
      toast.success(
        isEdit ? t('inspections.messages.updated') : t('inspections.messages.created'),
      )
      queryClient.invalidateQueries({ queryKey: ['inspections'] })
      const newId = (res.data as { data: Inspection }).data?.id
      router.push(newId ? `/inspections/${newId}` : '/inspections')
    },
    onError: (err: { response?: { data?: { message?: string } } }) => {
      toast.error(err?.response?.data?.message || t('common.somethingWentWrong'))
    },
  })

  const onSubmit = (values: FormValues) => {
    save.mutate({
      project_id: Number(values.project_id),
      site_id: Number(values.site_id),
      template_id: values.template_id ? Number(values.template_id) : null,
      inspected_at: values.inspected_at || null,
    })
  }

  const projects = projectsData?.data.data ?? []
  const sites = sitesData?.data.data ?? []
  const templates = templatesData?.data.data ?? []

  return (
    <div className="space-y-5">
      <div className="animate-fade-in-up flex items-center gap-3">
        <Link href="/inspections">
          <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('inspections.edit') : t('inspections.create')}
        </h1>
      </div>

      <form onSubmit={handleSubmit(onSubmit)}>
        <Card elevated>
          <div className="grid gap-4 sm:grid-cols-2">
            <Select
              label={t('inspections.project')}
              {...register('project_id', { required: true })}
              options={[
                { value: '', label: t('inspections.selectProject') },
                ...projects.map((p) => ({ value: String(p.id), label: p.name })),
              ]}
            />
            <Select
              label={t('inspections.site')}
              {...register('site_id', { required: true })}
              options={[
                { value: '', label: t('inspections.selectSite') },
                ...sites.map((s) => ({ value: String(s.id), label: s.name })),
              ]}
            />
            {!isEdit && (
              <Select
                label={t('inspections.template')}
                {...register('template_id')}
                options={[
                  { value: '', label: t('inspections.selectTemplate') },
                  ...templates.map((tmpl) => ({ value: String(tmpl.id), label: tmpl.name })),
                ]}
              />
            )}
            <Input
              type="datetime-local"
              label={t('inspections.inspectedAt')}
              {...register('inspected_at')}
            />
          </div>
          <div className="mt-4">
            <Button type="submit" disabled={save.isPending}>
              <Save size={14} />
              {t('common.save')}
            </Button>
          </div>
        </Card>
      </form>
    </div>
  )
}
