'use client';

import type { ComponentProps } from 'react';
import { useRef } from 'react';
import type { FieldErrors, UseFormRegister } from 'react-hook-form';
import { Loader2 } from 'lucide-react';

import { FormField } from '@/components/form';
import { ProjectSelect } from '@/components/lookups/ProjectSelect';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';

import type { PackageFormValues } from '../hooks/usePackageForm';

interface PackageDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  packageId?: string;
  projectId: string;
  onProjectChange: (projectId: string) => void;
  register: UseFormRegister<PackageFormValues>;
  errors: FieldErrors<PackageFormValues>;
  isSubmitted: boolean;
  onSubmit: ComponentProps<'form'>['onSubmit'];
  canSubmit: boolean;
  isSaving: boolean;
}

export function PackageDialog({
  open,
  onOpenChange,
  packageId,
  projectId,
  onProjectChange,
  register,
  errors,
  isSubmitted,
  onSubmit,
  canSubmit,
  isSaving,
}: PackageDialogProps) {
  const projectSelectPortalRef = useRef<HTMLDivElement | null>(null);
  const projectErrorMessage = isSubmitted
    ? errors.project_id?.message
    : undefined;
  const nameErrorMessage = isSubmitted ? errors.name?.message : undefined;
  const startErrorMessage = isSubmitted
    ? errors.chainage_start_km?.message
    : undefined;
  const endErrorMessage = isSubmitted
    ? errors.chainage_end_km?.message
    : undefined;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent
        className="flex max-h-[calc(100vh-2rem)] flex-col gap-0 p-0 sm:max-w-2xl"
        onOpenAutoFocus={(event) => event.preventDefault()}
      >
        <DialogHeader className="shrink-0 border-b px-6 py-4 pr-12">
          <DialogTitle className="text-lg leading-none font-semibold tracking-tight">
            {packageId ? 'Edit Package' : 'Create Package'}
          </DialogTitle>
          <DialogDescription className="text-sm">
            Manage package details and optional chainage range.
          </DialogDescription>
        </DialogHeader>

        <form
          noValidate
          onSubmit={onSubmit}
          className="flex min-h-0 flex-1 flex-col"
        >
          <div className="max-h-[58vh] space-y-6 overflow-y-auto px-6 py-4">
            <section className="space-y-4">
              <div className="space-y-1">
                <h3 className="text-sm font-semibold">Basic details</h3>
                <p className="text-sm text-muted-foreground">
                  Project binding, package name, and region.
                </p>
              </div>

              {!packageId ? (
                <FormField label="Project" required error={projectErrorMessage}>
                  <ProjectSelect
                    value={projectId}
                    onValueChange={onProjectChange}
                    enabled={open}
                    disabled={isSaving}
                    portalContainer={projectSelectPortalRef}
                  />
                  <input
                    type="hidden"
                    {...register('project_id')}
                    value={projectId}
                    readOnly
                  />
                </FormField>
              ) : null}

              <div className="grid gap-4 md:grid-cols-2">
                <FormField
                  id="package-name"
                  label="Package Name"
                  required
                  error={nameErrorMessage}
                >
                  <Input
                    id="package-name"
                    placeholder="Enter package name"
                    aria-invalid={!!nameErrorMessage}
                    {...register('name')}
                  />
                </FormField>

                <FormField id="package-region" label="Region">
                  <Input
                    id="package-region"
                    placeholder="Enter region"
                    {...register('region')}
                  />
                </FormField>
              </div>
            </section>

            <section className="space-y-4">
              <div className="space-y-1">
                <h3 className="text-sm font-semibold">Chainage range</h3>
                <p className="text-sm text-muted-foreground">
                  start and end kilometre values.
                </p>
              </div>

              <div className="grid gap-4 md:grid-cols-2">
                <FormField
                  id="package-start"
                  label="Start Chainage"
                  error={startErrorMessage}
                >
                  <Input
                    id="package-start"
                    type="number"
                    step="1"
                    min="0"
                    placeholder="Enter start chainage"
                    aria-invalid={!!startErrorMessage}
                    {...register('chainage_start_km')}
                  />
                </FormField>

                <FormField
                  id="package-end"
                  label="End Chainage"
                  error={endErrorMessage}
                >
                  <Input
                    id="package-end"
                    type="number"
                    step="1"
                    min="0"
                    placeholder="Enter end chainage"
                    aria-invalid={!!endErrorMessage}
                    {...register('chainage_end_km')}
                  />
                </FormField>
              </div>
            </section>
          </div>

          <DialogFooter className="shrink-0 border-t px-6 py-4">
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={isSaving}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={isSaving || !canSubmit}>
              {isSaving ? (
                <Loader2 className="mr-2 size-4 animate-spin" />
              ) : null}
              {packageId ? 'Update Package' : 'Create Package'}
            </Button>
          </DialogFooter>
        </form>

        <div ref={projectSelectPortalRef} />
      </DialogContent>
    </Dialog>
  );
}
