'use client';

import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Plus, Layers } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Modal } from '@/components/ui/modal';
import { useCreateSector } from '@/services/sectors/queries';
import { useDistricts } from '@/services/districts/queries';

// 1. Client-side Form Validation Schema (districtId made optional for standalone creation)
export const sectorFormSchema = z.object({
  name: z.string().min(2, 'Sector structural name must be at least 2 characters.'),
  code: z
    .string()
    .min(2, 'Short code must be at least 2 characters.')
    .max(10, 'Short code must be 10 characters or less.')
    .regex(/^[A-Za-z0-9-]+$/, 'Code must be alphanumeric (letters, numbers, hyphens).'),
  districtId: z.string().optional(),
});

export type SectorFormValues = z.infer<typeof sectorFormSchema>;

export default function CreateSectorModal({ onClose }: { onClose: () => void }) {
  const [apiError, setApiError] = useState<string | null>(null);

  const { data: districtData } = useDistricts(1, '');
  const createMutation = useCreateSector();

  const {
    register,
    handleSubmit,
    watch,
    setValue,
    formState: { errors, isSubmitting },
  } = useForm<SectorFormValues>({
    resolver: zodResolver(sectorFormSchema),
    defaultValues: {
      name: '',
      code: '',
      districtId: '',
    },
  });

  const codeValue = watch('code');

  const onSubmit = async (values: SectorFormValues) => {
    setApiError(null);
    try {
      await createMutation.mutateAsync({
        name: values.name.trim(),
        code: values.code.trim().toUpperCase(),
        districtId: values.districtId ? values.districtId : undefined,
      });
      onClose();
    } catch (err: any) {
      setApiError(err?.response?.data?.message || 'Failed to construct system sector.');
    }
  };

  return (
    <Modal onClose={onClose} icon={Layers} title="Deploy Standalone Operations Sector Unit">
      <form onSubmit={handleSubmit(onSubmit)} className="p-4 space-y-4">
        {apiError && (
          <div className="p-2.5 rounded-lg border border-destructive/20 bg-destructive/5 text-destructive text-[10px] font-medium">
            {apiError}
          </div>
        )}

        <div className="space-y-3">
          {/* Sector Name */}
          <div>
            <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 mb-1">
              Sector Name *
            </label>
            <input
              type="text"
              {...register('name')}
              placeholder="e.g., Healthcare & Medical"
              className={`w-full text-xs font-medium px-3 py-2 border bg-background rounded-lg text-foreground focus:outline-none ${
                errors.name ? 'border-destructive focus:border-destructive' : 'border-border/40 focus:border-primary'
              }`}
            />
            {errors.name && (
              <p className="text-[10px] font-medium text-destructive mt-1">{errors.name.message}</p>
            )}
          </div>

          {/* Sector Short Code */}
          <div>
            <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 mb-1">
              Sector Short Code *
            </label>
            <input
              type="text"
              {...register('code')}
              onChange={(e) => {
                const sanitized = e.target.value.replace(/[^a-zA-Z0-9-]/g, '').toUpperCase();
                setValue('code', sanitized, { shouldValidate: true });
              }}
              placeholder="e.g., HEA"
              maxLength={10}
              className={`w-full text-xs font-mono font-semibold px-3 py-2 border bg-background rounded-lg text-foreground focus:outline-none uppercase ${
                errors.code ? 'border-destructive focus:border-destructive' : 'border-border/40 focus:border-primary'
              }`}
            />
            {errors.code && (
              <p className="text-[10px] font-medium text-destructive mt-1">{errors.code.message}</p>
            )}

            <p className="text-[9px] text-muted-foreground mt-1.5 flex items-center gap-1 font-mono">
              <span className="font-semibold text-primary/80">Registered Code:</span>
              <span className="bg-muted px-1.5 py-0.5 rounded text-foreground font-bold">
                {codeValue ? codeValue.toUpperCase() : 'CODE'}
              </span>
            </p>
          </div>

          {/* Optional Initial District Assignment */}
          {/* <div>
            <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 mb-1">
              Initial District Mapping (Optional)
            </label>
            <select
              {...register('districtId')}
              className="w-full text-xs font-medium px-2 py-2 border border-border/40 bg-background rounded-lg text-foreground focus:outline-none focus:border-primary"
            >
              <option value="">None (Create Solely as Global Sector)</option>
              {districtData?.items?.map((d: any) => (
                <option key={d.id} value={d.id}>
                  {d.name} ({d.state?.code ? `${d.state.code}-` : ''}{d.code})
                </option>
              ))}
            </select>
            <p className="text-[9px] text-muted-foreground/70 mt-1">
              Sectors can be linked to additional districts later via District-Sector combinations.
            </p>
          </div> */}
        </div>

        {/* Footer Actions */}
        <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"
          >
            Cancel
          </Button>
          <Button
            type="submit"
            disabled={createMutation.isPending || isSubmitting}
            className="h-8 rounded-lg px-3 text-xs font-semibold shadow-sm gap-1.5"
          >
            <Plus className="h-3.5 w-3.5 stroke-[2.5]" />
            <span>{createMutation.isPending || isSubmitting ? 'Constructing...' : 'Deploy Sector'}</span>
          </Button>
        </div>
      </form>
    </Modal>
  );
}