import { useEffect } from 'react'
import { z } from 'zod'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { ArrowLeft, Loader2 } from 'lucide-react'
import type { AdminCourseRecord, AdminScheduleRecord } from '@/lib/api/types'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Textarea } from '@/components/ui/textarea'

export const scheduleFormSchema = z.object({
  courseId: z.coerce.number().min(1, 'Egitim seciniz'),
  startDate: z.string().min(1, 'Baslangic tarihi zorunludur'),
  endDate: z.string().optional(),
  location: z.string().min(2, 'Lokasyon zorunludur'),
  instructor: z.string().optional(),
  quota: z.coerce.number().min(1, 'Kontenjan en az 1 olmalidir'),
  enrolledCount: z.coerce
    .number()
    .min(0, 'Kayitli sayisi 0 veya daha buyuk olmalidir'),
  priceOverride: z.string().optional(),
  status: z.string().min(1, 'Durum seçiniz'),
  notes: z.string().optional(),
})

export type ScheduleFormInput = z.input<typeof scheduleFormSchema>
export type ScheduleFormValues = z.output<typeof scheduleFormSchema>

export function ScheduleForm({
  schedule,
  courses,
  isPending,
  onCancel,
  onSubmit,
}: {
  schedule: AdminScheduleRecord | null
  courses: AdminCourseRecord[]
  isPending: boolean
  onCancel: () => void
  onSubmit: (values: ScheduleFormValues) => Promise<void>
}) {
  const form = useForm<ScheduleFormInput, undefined, ScheduleFormValues>({
    resolver: zodResolver(scheduleFormSchema),
    defaultValues: {
      courseId: Number(schedule?.courseId ?? 0),
      startDate: schedule?.startDate ?? '',
      endDate: schedule?.endDate ?? '',
      location: schedule?.location ?? '',
      instructor: schedule?.instructor ?? '',
      quota: schedule?.quota ?? 10,
      enrolledCount: schedule?.enrolledCount ?? 0,
      priceOverride:
        schedule?.priceOverride === null ||
        schedule?.priceOverride === undefined
          ? ''
          : String(schedule.priceOverride),
      status: schedule?.status ?? 'planned',
      notes: schedule?.notes ?? '',
    } satisfies ScheduleFormInput,
  })

  useEffect(() => {
    form.reset({
      courseId: Number(schedule?.courseId ?? 0),
      startDate: schedule?.startDate ?? '',
      endDate: schedule?.endDate ?? '',
      location: schedule?.location ?? '',
      instructor: schedule?.instructor ?? '',
      quota: schedule?.quota ?? 10,
      enrolledCount: schedule?.enrolledCount ?? 0,
      priceOverride:
        schedule?.priceOverride === null ||
        schedule?.priceOverride === undefined
          ? ''
          : String(schedule.priceOverride),
      status: schedule?.status ?? 'planned',
      notes: schedule?.notes ?? '',
    })
  }, [form, schedule])

  return (
    <Card className='border-border/70 shadow-sm'>
      <CardHeader className='border-b border-border/70 bg-muted/20 px-5 py-4'>
        <div className='flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between'>
          <div className='space-y-1'>
            <CardTitle>
              {schedule ? 'Takvimi düzenle' : 'Yeni takvim oluştur'}
            </CardTitle>
            <CardDescription>
              Yaklaşan programlar ve kurs planlama modülü bu kayıtlardan
              beslenir.
            </CardDescription>
          </div>
          <Button
            type='button'
            variant='ghost'
            size='sm'
            className='h-8 rounded-lg px-2 text-muted-foreground sm:shrink-0'
            onClick={onCancel}
          >
            <ArrowLeft />
            Listeye dön
          </Button>
        </div>
      </CardHeader>
      <CardContent className='p-4 md:p-5'>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(async (values) => {
              await onSubmit(values)
            })}
            className='space-y-4'
          >
            {/* Program bilgileri */}
            <div className='rounded-3xl border border-border/70 bg-card p-4 shadow-sm'>
              <div className='mb-3 border-b border-border/70 pb-3'>
                <p className='text-sm font-semibold'>Program bilgileri</p>
                <p className='text-sm text-muted-foreground'>
                  Eğitim seçimi, durum ve tarih aralığı
                </p>
              </div>
              <div className='space-y-3'>
                <div className='grid gap-3 md:grid-cols-2'>
                  <FormField
                    control={form.control}
                    name='courseId'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Eğitim</FormLabel>
                        <Select
                          value={String(field.value || '')}
                          onValueChange={(value) =>
                            field.onChange(Number(value))
                          }
                        >
                          <FormControl>
                            <SelectTrigger className='w-full'>
                              <SelectValue placeholder='Eğitim seçiniz' />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {courses.map((course) => (
                              <SelectItem
                                key={course.id}
                                value={String(course.id)}
                              >
                                {course.title}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name='status'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Durum</FormLabel>
                        <Select
                          value={field.value}
                          onValueChange={field.onChange}
                        >
                          <FormControl>
                            <SelectTrigger className='w-full'>
                              <SelectValue placeholder='Durum seçiniz' />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value='planned'>Planlandı</SelectItem>
                            <SelectItem value='open'>Açık</SelectItem>
                            <SelectItem value='closed'>Kapandı</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <div className='grid gap-3 md:grid-cols-2'>
                  <FormField
                    control={form.control}
                    name='startDate'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Başlangıç tarihi</FormLabel>
                        <FormControl>
                          <Input {...field} type='date' />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name='endDate'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Bitiş tarihi</FormLabel>
                        <FormControl>
                          <Input {...field} type='date' />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </div>
            </div>

            {/* Lokasyon ve kontenjan */}
            <div className='rounded-3xl border border-border/70 bg-card p-4 shadow-sm'>
              <div className='mb-3 border-b border-border/70 pb-3'>
                <p className='text-sm font-semibold'>Lokasyon ve kontenjan</p>
                <p className='text-sm text-muted-foreground'>
                  Eğitim yeri, eğitmen ve koltuk bilgileri
                </p>
              </div>
              <div className='space-y-3'>
                <div className='grid gap-3 md:grid-cols-2'>
                  <FormField
                    control={form.control}
                    name='location'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Lokasyon</FormLabel>
                        <FormControl>
                          <Input {...field} placeholder='Kadıköy / Online' />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name='instructor'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Eğitmen</FormLabel>
                        <FormControl>
                          <Input
                            {...field}
                            placeholder='Opsiyonel eğitmen adı'
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <div className='grid gap-3 md:grid-cols-3'>
                  <FormField
                    control={form.control}
                    name='quota'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Kontenjan</FormLabel>
                        <FormControl>
                          <Input
                            name={field.name}
                            ref={field.ref}
                            onBlur={field.onBlur}
                            disabled={field.disabled}
                            type='number'
                            min={1}
                            value={String(field.value ?? 1)}
                            onChange={(e) => field.onChange(e.target.value)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name='enrolledCount'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Kayıtlı sayısı</FormLabel>
                        <FormControl>
                          <Input
                            name={field.name}
                            ref={field.ref}
                            onBlur={field.onBlur}
                            disabled={field.disabled}
                            type='number'
                            min={0}
                            value={String(field.value ?? 0)}
                            onChange={(e) => field.onChange(e.target.value)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name='priceOverride'
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Fiyat override</FormLabel>
                        <FormControl>
                          <Input {...field} placeholder='Opsiyonel' />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </div>
            </div>

            {/* Notlar */}
            <div className='rounded-3xl border border-border/70 bg-card p-4 shadow-sm'>
              <div className='mb-3 border-b border-border/70 pb-3'>
                <p className='text-sm font-semibold'>Notlar</p>
                <p className='text-sm text-muted-foreground'>
                  Operasyon ve iç notlar
                </p>
              </div>
              <FormField
                control={form.control}
                name='notes'
                render={({ field }) => (
                  <FormItem>
                    <FormControl>
                      <Textarea
                        {...field}
                        rows={4}
                        placeholder='Operasyon notları...'
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className='flex flex-wrap justify-end gap-3 border-t border-border/70 pt-4'>
              <Button type='button' variant='outline' onClick={onCancel}>
                Vazgeç
              </Button>
              <Button type='submit' className='rounded-xl' disabled={isPending}>
                {isPending && <Loader2 className='animate-spin' />}
                {schedule ? 'Kaydet' : 'Takvim oluştur'}
              </Button>
            </div>
          </form>
        </Form>
      </CardContent>
    </Card>
  )
}
