import { Field, FieldLabel } from '@/components/ui/field';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';
import type { Sport } from '@repo/api-contract';
import { Check } from 'lucide-react';
import type { UseFormReturn } from 'react-hook-form';

type CourtsSetupStepProps = {
  form: UseFormReturn<any>;
  sports: Sport[];
};

const DAYS_OF_WEEK = [
  { value: 'MONDAY', label: 'Lun' },
  { value: 'TUESDAY', label: 'Mar' },
  { value: 'WEDNESDAY', label: 'Mié' },
  { value: 'THURSDAY', label: 'Jue' },
  { value: 'FRIDAY', label: 'Vie' },
  { value: 'SATURDAY', label: 'Sáb' },
  { value: 'SUNDAY', label: 'Dom' },
] as const;

export function CourtsSetupStep({ form, sports }: CourtsSetupStepProps) {
  const setupCourts = form.watch('setupCourts') as boolean | undefined;
  const courtDaysOfWeek = form.watch('courtDaysOfWeek') as string[] | undefined;
  const errors = form.formState.errors;

  const toggleDay = (day: string) => {
    const current = courtDaysOfWeek ?? [];
    const next = current.includes(day) ? current.filter((d) => d !== day) : [...current, day];
    form.setValue('courtDaysOfWeek', next, { shouldValidate: true });
  };

  return (
    <div className="space-y-4">
      <div>
        <h2 className="text-lg font-semibold">Crear canchas</h2>
        <p className="text-sm text-muted-foreground">
          Configurá una cancha para empezar a recibir reservas.
        </p>
      </div>

      <label className="flex items-center gap-3 rounded-lg border p-4 cursor-pointer hover:bg-muted/50 transition-colors">
        <input
          type="checkbox"
          className="size-4 accent-primary"
          checked={setupCourts ?? false}
          onChange={(e) => {
            form.setValue('setupCourts', e.target.checked, { shouldValidate: true });
            if (!e.target.checked) {
              form.setValue('courtSportId', undefined);
              form.setValue('courtStartTime', undefined);
              form.setValue('courtEndTime', undefined);
              form.setValue('courtDaysOfWeek', undefined);
            }
          }}
        />
        <div>
          <p className="font-medium text-sm">Sí, crear una cancha ahora</p>
          <p className="text-xs text-muted-foreground">
            Vas a poder agregar más canchas después desde el panel de administración.
          </p>
        </div>
      </label>

      {setupCourts && (
        <div className="space-y-4 pl-6 border-l-2 border-primary/20">
          <Field data-invalid={Boolean(errors.courtSportId)}>
            <FieldLabel htmlFor="court-sport">Deporte</FieldLabel>
            <select
              id="court-sport"
              className="h-10 w-full rounded-md border bg-background px-3 text-sm aria-invalid:border-destructive"
              aria-invalid={Boolean(errors.courtSportId)}
              {...form.register('courtSportId')}
            >
              <option value="">Seleccioná un deporte</option>
              {sports.map((sport) => (
                <option key={sport.id} value={sport.id}>
                  {sport.name}
                </option>
              ))}
            </select>
            {errors.courtSportId && (
              <p className="text-sm text-destructive mt-1">
                {String(errors.courtSportId.message ?? '')}
              </p>
            )}
          </Field>

          <div className="grid grid-cols-2 gap-3">
            <Field data-invalid={Boolean(errors.courtStartTime)}>
              <FieldLabel htmlFor="court-start">Horario desde</FieldLabel>
              <Input
                id="court-start"
                type="time"
                defaultValue="08:00"
                aria-invalid={Boolean(errors.courtStartTime)}
                {...form.register('courtStartTime')}
              />
              {errors.courtStartTime && (
                <p className="text-sm text-destructive mt-1">
                  {String(errors.courtStartTime.message ?? '')}
                </p>
              )}
            </Field>

            <Field data-invalid={Boolean(errors.courtEndTime)}>
              <FieldLabel htmlFor="court-end">Horario hasta</FieldLabel>
              <Input
                id="court-end"
                type="time"
                defaultValue="22:00"
                aria-invalid={Boolean(errors.courtEndTime)}
                {...form.register('courtEndTime')}
              />
              {errors.courtEndTime && (
                <p className="text-sm text-destructive mt-1">
                  {String(errors.courtEndTime.message ?? '')}
                </p>
              )}
            </Field>
          </div>

          <div>
            <Label className="mb-2 block text-sm">Días de la semana</Label>
            <div className="flex flex-wrap gap-2">
              {DAYS_OF_WEEK.map((day) => {
                const isSelected = courtDaysOfWeek?.includes(day.value) ?? false;
                return (
                  <button
                    key={day.value}
                    type="button"
                    onClick={() => toggleDay(day.value)}
                    className={cn(
                      'flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-medium transition-all',
                      isSelected
                        ? 'border-primary bg-primary/10 text-primary'
                        : 'border-border text-muted-foreground hover:border-muted-foreground/30'
                    )}
                  >
                    {isSelected && <Check className="size-3" />}
                    {day.label}
                  </button>
                );
              })}
            </div>
            {errors.courtDaysOfWeek && (
              <p className="text-sm text-destructive mt-1">
                {String(errors.courtDaysOfWeek.message ?? '')}
              </p>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
