'use client';

import type { ReactNode } from 'react';
import { useForm } from 'react-hook-form';
import { BookOpen, Plus } from 'lucide-react';
import { Modal } from '@/components/ui/modal';
import { Button } from '@/components/ui/button';
import { useCreateCourse } from '@/services/courses/queries';
import { useAllSectors } from '@/services/sectors/queries';
import type { CreateCourseInput } from '@/services/courses/types';

interface CreateCourseModalProps {
  onClose: () => void;
}

export function CreateCourseModal({ onClose }: CreateCourseModalProps) {
  const create = useCreateCourse();
  // Fetch only active sectors for the dropdown
  const { data: sectors, isLoading: isLoadingSectors } = useAllSectors('', 'all');

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<CreateCourseInput>({
    defaultValues: {
      durationWeeks: 4, // Providing a reasonable default
    },
  });

  // Handle form submission
  const onSubmit = handleSubmit((data) => {
    create.mutate(data, {
      onSuccess: () => {
        // Close modal on successful creation
        onClose();
      },
    });
  });

  return (
    <Modal onClose={onClose} title="Create Course" icon={BookOpen}>
      <form className="space-y-4 p-4" onSubmit={onSubmit}>
        <Field label="Course Name" error={errors.name?.message}>
          <input
            className="w-full rounded-lg border border-border/40 bg-background px-3 py-2 text-xs focus:border-primary/60 focus:ring-1 focus:ring-primary/60"
            placeholder="Enter course name"
            {...register('name', {
              required: 'Course name is required',
              minLength: {
                value: 3,
                message: 'Name must be at least 3 characters',
              },
            })}
          />
        </Field>

        <Field label="Sector" error={errors.sectorId?.message}>
          <select
            className="w-full rounded-lg border border-border/40 bg-background px-3 py-2 text-xs focus:border-primary/60 focus:ring-1 focus:ring-primary/60 disabled:cursor-not-allowed disabled:opacity-60"
            disabled={isLoadingSectors}
            {...register('sectorId', {
              required: 'Please select a sector',
            })}
          >
            <option value="">
              {isLoadingSectors ? 'Loading sectors...' : 'Select active sector'}
            </option>
            {sectors?.items?.map((sector: any) => (
              <option key={sector.id} value={sector.id}>
                {sector.name} ({sector.code})
              </option>
            ))}
          </select>
        </Field>

        <Field label="Duration (Weeks)" error={errors.durationWeeks?.message}>
          <input
            className="w-full rounded-lg border border-border/40 bg-background px-3 py-2 text-xs focus:border-primary/60 focus:ring-1 focus:ring-primary/60"
            type="number"
            min="1"
            placeholder="e.g. 8"
            {...register('durationWeeks', {
              required: 'Duration is required',
              valueAsNumber: true,
              min: {
                value: 1,
                message: 'Duration must be at least 1 week',
              },
            })}
          />
        </Field>

        <Field label="Description (Optional)">
          <textarea
            className="min-h-24 w-full rounded-lg border border-border/40 bg-background px-3 py-2 text-xs focus:border-primary/60 focus:ring-1 focus:ring-primary/60"
            placeholder="Briefly describe the course content..."
            {...register('description')}
          />
        </Field>

        {/* ACTION BUTTON AXIS */}
        <div className="flex items-center justify-end gap-2 border-t border-border/10 pt-3 mt-4">
          <Button
            type="button"
            variant="ghost"
            onClick={onClose}
            className="h-8 rounded-lg px-3 text-xs font-semibold transition-colors"
          >
            Cancel
          </Button>
          <Button
            type="submit"
            disabled={create.isPending}
            className="h-8 rounded-lg px-3 text-xs font-semibold shadow-sm gap-1.5 transition-transform duration-150 active:scale-95"
          >
            <Plus className="h-3.5 w-3.5 stroke-[2.5]" />
            <span>{create.isPending ? 'Creating...' : 'Create Course'}</span>
          </Button>
        </div>
        
      </form>
    </Modal>
  );
}

interface FieldProps {
  label: string;
  error?: string;
  children: ReactNode;
}

function Field({ label, error, children }: FieldProps) {
  return (
    <label className="block space-y-1">
      <span className="text-xs font-semibold text-foreground">{label}</span>
      {children}
      {error && <span className="block text-xs text-destructive pt-0.5">{error}</span>}
    </label>
  );
}