'use client';

import React, { useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useForm, useFieldArray, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { State, City } from 'country-state-city';
import { z } from 'zod';
import {
  Building2,
  MapPin,
  FileCheck,
  Upload,
  UserCheck,
  ShieldCheck,
  ArrowLeft,
  Check,
  Plus,
  Trash2,
  Eye,
  EyeOff,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useProvisionInstitutesAdmin } from '@/services/institutes/queries';
import { useAllDistricts } from '@/services/districts/queries';
import { useAllSectors } from '@/services/sectors/queries';
import { useSystemUSerRoles } from '@/services/roles/queries';
import { DOCUMENT_TYPES } from '@/data/document-types';

const instituteProvisionSchema = z.object({
  institute: z.object({
    name: z.string().min(1, 'Institute name is required'),
    code: z.string().min(1, 'Institute code is required'),
    districtId: z.string().min(1, 'District selection is required'),
    sectorId: z.string().min(1, 'Sector selection is required'),
    address: z.string().optional(),
    contactPerson: z.string().optional(),
    contactMobile: z.string().optional(),
    contactEmail: z.string().email('Invalid email').optional().or(z.literal('')),
    assignedApproverId: z.string().optional(),
  }),
  admin: z.object({
    firstName: z.string().min(1, 'First name is required'),
    lastName: z.string().min(1, 'Last name is required'),
    email: z.string().email('Invalid login email'),
    password: z.string().min(8, 'Password must be at least 8 characters'),
    phone: z.string().optional(),
  }),
  profile: z.object({
    registeredOfficeAddress: z.string().min(1, 'Office address is required'),
    city: z.string().min(1, 'City is required'),
    state: z.string().default('Maharashtra'),
    postalCode: z.string().min(6, 'Valid 6-digit PIN code required'),
    organizationName: z.string().optional(),
    taxIdentifier: z.string().optional(),
    corporateRegNumber: z.string().optional(),
    officialLandline: z.string().optional(),
    aadhaarNumber: z.string().optional(),
    panNumber: z.string().optional(),
    bankAccountNumber: z.string().optional(),
    bankIFSC: z.string().optional(),
    bankName: z.string().optional(),
    bankAccountHolder: z.string().optional(),
  }),
  kyc: z.object({
    isDelegated: z.boolean(),
    assignedToRole: z.string().optional(),
    assignedToUserId: z.string().optional(),
    documents: z.array(
      z.object({
        type: z.string(),
        file: z.any(),
      })
    ),
  }),
});

type FormValues = z.infer<typeof instituteProvisionSchema>;

export default function NewInstitutePage() {
  const router = useRouter();
  const { data: districtsData } = useAllDistricts();
  const { data: systemRoles } = useSystemUSerRoles();
  const provisionMutation = useProvisionInstitutesAdmin();

  const rawDistricts = (districtsData as any)?.items || districtsData || [];
  const [showPassword, setShowPassword] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);

  // Fetch all Indian states
  const indianStates = useMemo(() => State.getStatesOfCountry('IN'), []);

  const {
    register,
    control,
    handleSubmit,
    watch,
    setValue,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(instituteProvisionSchema),
    defaultValues: {
      institute: {
        name: '',
        code: '',
        districtId: '',
        sectorId: '',
        address: '',
        contactPerson: '',
        contactMobile: '',
        contactEmail: '',
        assignedApproverId: '',
      },
      admin: {
        firstName: '',
        lastName: '',
        email: '',
        password: '',
        phone: '',
      },
      profile: {
        registeredOfficeAddress: '',
        city: '',
        state: 'Maharashtra',
        postalCode: '',
        organizationName: '',
        taxIdentifier: '',
        corporateRegNumber: '',
        officialLandline: '',
        aadhaarNumber: '',
        panNumber: '',
        bankAccountNumber: '',
        bankIFSC: '',
        bankName: '',
        bankAccountHolder: '',
      },
      kyc: {
        isDelegated: false,
        assignedToRole: 'KYC_OFFICER',
        assignedToUserId: '',
        documents: [
          { type: 'AADHAAR', file: null },
          { type: 'PAN', file: null },
        ],
      },
    },
  });

  const { fields: documentFields, append: appendDocument, remove: removeDocument } =
    useFieldArray({ control, name: 'kyc.documents' });

  const selectedStateName = watch('profile.state');

  // Match ISO Code for city lookup
  const selectedStateObj = useMemo(() => {
    return indianStates.find(
      (s) => s.name === selectedStateName || s.isoCode === selectedStateName
    );
  }, [indianStates, selectedStateName]);

  // Fetch cities scoped strictly to the selected Indian state
  const availableCities = useMemo(() => {
    return selectedStateObj ? City.getCitiesOfState('IN', selectedStateObj.isoCode) : [];
  }, [selectedStateObj]);

  const selectedDistrictId = watch('institute.districtId');
  const isKycDelegated = watch('kyc.isDelegated');
  const assignedRole = watch('kyc.assignedToRole');

  const { data: sectorsData, isLoading: isLoadingSectors } = useAllSectors(
    selectedDistrictId,
    'active'
  );
  const sectors = (sectorsData as any)?.items || sectorsData || [];

  const onSubmit = async (data: FormValues) => {
    setSubmitError(null);
    try {
      await provisionMutation.mutateAsync({
        institute: {
          ...data.institute,
          code: data.institute.code.toUpperCase().trim(),
        },
        admin: {
          ...data.admin,
          email: data.admin.email.toLowerCase().trim(),
        },
        profile: data.profile,
        kyc: {
          isDelegated: data.kyc.isDelegated,
          assignedToRole: data.kyc.isDelegated ? data.kyc.assignedToRole : null,
          assignedToUserId: data.kyc.isDelegated ? data.kyc.assignedToUserId : null,
          documents: !data.kyc.isDelegated
            ? data.kyc.documents.filter((d) => d.file !== null)
            : [],
        },
      });

      router.push('/institutes');
    } catch (err: any) {
      setSubmitError(
        err?.response?.data?.message ||
          'Failed to provision institute and administrative node.'
      );
    }
  };

  return (
    <div className="max-w-7xl space-y-6 animate-in fade-in duration-200 select-none min-h-screen relative pb-10">
      <div className="flex items-center gap-3">
        <Button
          type="button"
          variant="outline"
          size="icon"
          className="h-8 w-8 rounded-lg"
          onClick={() => router.back()}
        >
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <div>
          <h1 className="text-sm font-black tracking-widest text-foreground uppercase">
            Provision Campus Node & Admin Identity
          </h1>
          <p className="text-[11px] text-muted-foreground/70">
            Configure campus profile, map territorial parameters, register personal KYC credentials, and configure verifiers.
          </p>
        </div>
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-6 relative">
        {submitError && (
          <div className="p-3 bg-destructive/5 border border-destructive/20 text-destructive text-xs rounded-lg font-medium">
            {submitError}
          </div>
        )}

        {/* SECTION 1: INSTTTUTE WORKSPACE PROFILE */}
        <div className="border border-border/40 rounded-xl bg-surface p-4 space-y-4 shadow-sm">
          <div className="flex items-center gap-2 border-b border-border/10 pb-2">
            <Building2 className="h-4 w-4 text-primary" />
            <h2 className="text-xs font-bold uppercase tracking-wider text-foreground">
              Campus Profile Parameters
            </h2>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                Institute Full Name *
              </label>
              <input
                type="text"
                {...register('institute.name')}
                placeholder="e.g., National Technical Operations Center"
                className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
              />
              {errors.institute?.name && (
                <span className="text-[10px] text-destructive block mt-0.5">
                  {errors.institute.name.message}
                </span>
              )}
            </div>

            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                Unique Institute Code *
              </label>
              <input
                type="text"
                {...register('institute.code')}
                placeholder="INST-MUM-001"
                className="w-full text-xs font-mono font-bold px-3 py-2 border border-border/40 bg-background rounded-lg text-primary uppercase focus:outline-none focus:border-primary"
              />
              {errors.institute?.code && (
                <span className="text-[10px] text-destructive block mt-0.5">
                  {errors.institute.code.message}
                </span>
              )}
            </div>

            <div className="md:col-span-2">
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                Physical Campus Address
              </label>
              <input
                type="text"
                {...register('institute.address')}
                placeholder="Campus Sector Link, Lane Architecture, Industrial Zone"
                className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
              />
            </div>
          </div>
        </div>

        {/* SECTION 2: TOPOLOGY MAPPING */}
        <div className="border border-border/40 rounded-xl bg-surface p-4 space-y-4 shadow-sm">
          <div className="flex items-center gap-2 border-b border-border/10 pb-2">
            <MapPin className="h-4 w-4 text-primary" />
            <h2 className="text-xs font-bold uppercase tracking-wider text-foreground">
              Territorial Alignment
            </h2>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                District Boundary *
              </label>
              <select
                {...register('institute.districtId')}
                onChange={(e) => {
                  setValue('institute.districtId', e.target.value);
                  setValue('institute.sectorId', '');
                }}
                className="w-full text-xs p-2 border border-border/40 rounded-lg bg-background text-foreground focus:outline-none focus:border-primary"
              >
                <option value="">-- Choose District Target --</option>
                {rawDistricts.map((d: any) => (
                  <option key={d.id} value={d.id}>
                    {d.name}
                  </option>
                ))}
              </select>
              {errors.institute?.districtId && (
                <span className="text-[10px] text-destructive block mt-0.5">
                  {errors.institute.districtId.message}
                </span>
              )}
            </div>

            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                Sector Target *{' '}
                {isLoadingSectors && (
                  <span className="text-[9px] text-primary animate-pulse">
                    (loading sectors...)
                  </span>
                )}
              </label>
              <select
                {...register('institute.sectorId')}
                className="w-full text-xs p-2 border border-border/40 rounded-lg bg-background text-foreground focus:outline-none focus:border-primary"
                disabled={!selectedDistrictId || sectors.length === 0}
              >
                <option value="">
                  {!selectedDistrictId
                    ? '-- Select District First --'
                    : sectors.length === 0
                    ? 'No operational sectors found'
                    : '-- Choose Operational Sector --'}
                </option>
                {sectors.map((s: any) => (
                  <option key={s.id} value={s.id}>
                    {s.name}
                  </option>
                ))}
              </select>
              {errors.institute?.sectorId && (
                <span className="text-[10px] text-destructive block mt-0.5">
                  {errors.institute.sectorId.message}
                </span>
              )}
            </div>
          </div>
        </div>

        {/* SECTION 3: ADMIN CREDENTIALS */}
        <div className="border border-border/40 rounded-xl bg-surface p-4 space-y-4 shadow-sm">
          <div className="flex items-center gap-2 border-b border-border/10 pb-2">
            <ShieldCheck className="h-4 w-4 text-primary" />
            <h2 className="text-xs font-bold uppercase tracking-wider text-foreground">
              Institute Admin Authority Profile
            </h2>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                First Name *
              </label>
              <input
                type="text"
                {...register('admin.firstName')}
                className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
              />
              {errors.admin?.firstName && (
                <span className="text-[10px] text-destructive block mt-0.5">
                  {errors.admin.firstName.message}
                </span>
              )}
            </div>

            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                Last Name *
              </label>
              <input
                type="text"
                {...register('admin.lastName')}
                className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
              />
              {errors.admin?.lastName && (
                <span className="text-[10px] text-destructive block mt-0.5">
                  {errors.admin.lastName.message}
                </span>
              )}
            </div>

            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                Admin Sign-In Email *
              </label>
              <input
                type="email"
                {...register('admin.email')}
                placeholder="admin@institute.org"
                className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
              />
              {errors.admin?.email && (
                <span className="text-[10px] text-destructive block mt-0.5">
                  {errors.admin.email.message}
                </span>
              )}
            </div>

            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                Mobile Line
              </label>
              <input
                type="text"
                {...register('admin.phone')}
                placeholder="+91 XXXXX XXXXX"
                className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
              />
            </div>

            <div className="md:col-span-2">
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                Temporary Security Key *
              </label>
              <div className="relative flex items-center">
                <input
                  type={showPassword ? 'text' : 'password'}
                  {...register('admin.password')}
                  className="w-full text-xs font-mono pl-3 pr-9 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-2.5 p-1 text-muted-foreground/60 hover:text-foreground"
                >
                  {showPassword ? (
                    <EyeOff className="h-3.5 w-3.5" />
                  ) : (
                    <Eye className="h-3.5 w-3.5" />
                  )}
                </button>
              </div>
              {errors.admin?.password && (
                <span className="text-[10px] text-destructive block mt-0.5">
                  {errors.admin.password.message}
                </span>
              )}
            </div>
          </div>
        </div>

        {/* SECTION 4: CORPORATE REGISTERED PROFILE & BANKING */}
        <div className="border border-border/40 rounded-xl bg-surface p-4 space-y-4 shadow-sm">
          <div className="flex items-center gap-2 border-b border-border/10 pb-2">
            <Building2 className="h-4 w-4 text-primary" />
            <h2 className="text-xs font-bold uppercase tracking-wider text-foreground">
              Corporate Office & Financial Identifiers
            </h2>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            <div className="md:col-span-3">
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                Registered Office Address *
              </label>
              <input
                type="text"
                {...register('profile.registeredOfficeAddress')}
                placeholder="Suite, Building, Industrial Complex"
                className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
              />
              {errors.profile?.registeredOfficeAddress && (
                <span className="text-[10px] text-destructive block mt-0.5">
                  {errors.profile.registeredOfficeAddress.message}
                </span>
              )}
            </div>

            {/* Indian State Dropdown */}
            <div>
              <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 mb-1">
                State (India) *
              </label>
              <select
                {...register('profile.state')}
                onChange={(e) => {
                  setValue('profile.state', e.target.value);
                  setValue('profile.city', ''); // Reset city on state change
                }}
                className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg text-foreground focus:outline-none focus:border-primary cursor-pointer"
              >
                <option value="">-- Select Indian State --</option>
                {indianStates.map((st) => (
                  <option key={st.isoCode} value={st.name}>
                    {st.name}
                  </option>
                ))}
              </select>
            </div>

            {/* Indian City Dropdown */}
            <div>
              <label className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80 mb-1">
                City *
              </label>
              <select
                {...register('profile.city')}
                disabled={!selectedStateName || availableCities.length === 0}
                className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg text-foreground focus:outline-none focus:border-primary cursor-pointer disabled:opacity-50"
              >
                <option value="">
                  {!selectedStateName
                    ? '-- Select State First --'
                    : availableCities.length === 0
                    ? 'No cities available'
                    : '-- Select City --'}
                </option>
                {availableCities.map((ct) => (
                  <option key={`${ct.name}-${ct.latitude}`} value={ct.name}>
                    {ct.name}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                Postal Code *
              </label>
              <input
                type="text"
                {...register('profile.postalCode')}
                className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
              />
            </div>

            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                Aadhaar Card Number
              </label>
              <input
                type="text"
                {...register('profile.aadhaarNumber')}
                placeholder="XXXX XXXX XXXX"
                maxLength={14}
                className="w-full text-xs font-mono px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
              />
            </div>

            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                PAN Card Number
              </label>
              <input
                type="text"
                {...register('profile.panNumber')}
                placeholder="ABCDE1234F"
                maxLength={10}
                className="w-full text-xs font-mono uppercase px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
              />
            </div>

            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                Bank Account Number
              </label>
              <input
                type="text"
                {...register('profile.bankAccountNumber')}
                className="w-full text-xs font-mono px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
              />
            </div>

            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                Bank IFSC Code
              </label>
              <input
                type="text"
                {...register('profile.bankIFSC')}
                placeholder="SBIN000XXXX"
                maxLength={11}
                className="w-full text-xs font-mono uppercase px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
              />
            </div>

            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                Bank Name
              </label>
              <input
                type="text"
                {...register('profile.bankName')}
                className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
              />
            </div>

            <div>
              <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                Bank Account Holder
              </label>
              <input
                type="text"
                {...register('profile.bankAccountHolder')}
                className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg focus:outline-none focus:border-primary"
              />
            </div>
          </div>
        </div>

        {/* SECTION 5: KYC DELEGATION & FILE UPLOADS */}
        <div className="border border-border/40 rounded-xl bg-surface p-4 space-y-4 shadow-sm">
          <div className="flex items-center justify-between border-b border-border/10 pb-2">
            <div className="flex items-center gap-2">
              <FileCheck className="h-4 w-4 text-primary" />
              <h2 className="text-xs font-bold uppercase tracking-wider text-foreground">
                KYC Verification & Document Upload Workflow
              </h2>
            </div>
          </div>

          <div>
            <label className="flex items-center gap-2 cursor-pointer p-2.5 rounded-lg border border-border/30 bg-muted/20 hover:bg-muted/40 transition-colors">
              <input
                type="checkbox"
                {...register('kyc.isDelegated')}
                className="h-4 w-4 rounded border-border/40 text-primary focus:ring-primary"
              />
              <div>
                <span className="text-xs font-bold text-foreground block">
                  Delegate KYC Verification to Assigned Officer / Role
                </span>
                <span className="text-[10px] text-muted-foreground block">
                  Delegating hides immediate file uploads and routes verification to an authorized reviewer.
                </span>
              </div>
            </label>
          </div>

          {isKycDelegated ? (
            <div className="p-3.5 rounded-xl border border-primary/20 bg-primary/5 space-y-3">
              <div className="flex items-center gap-2 text-primary">
                <UserCheck className="h-4 w-4" />
                <span className="text-xs font-bold uppercase tracking-wider">
                  KYC Verification Role Assignment
                </span>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <div>
                  <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                    Designated Verification Role
                  </label>
                  <select
                    {...register('kyc.assignedToRole')}
                    onChange={(e) => {
                      setValue('kyc.assignedToRole', e.target.value);
                      setValue('kyc.assignedToUserId', '');
                    }}
                    className="w-full text-xs p-2 border border-border/40 rounded-lg bg-background text-foreground focus:outline-none focus:border-primary"
                  >
                    <option value="KYC_OFFICER">KYC Officer</option>
                    <option value="HR">HR Department</option>
                    <option value="BDM">Business Development Manager (BDM)</option>
                    <option value="ADMIN">System Administrator</option>
                  </select>
                </div>

                <div>
                  <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                    Assign Specific Verifier
                  </label>
                  <select
                    {...register('kyc.assignedToUserId')}
                    className="w-full text-xs p-2 border border-border/40 rounded-lg bg-background text-foreground focus:outline-none focus:border-primary"
                  >
                    <option value="">
                      {systemRoles && systemRoles.length > 0
                        ? '-- Select Verifier (Or Leave Blank) --'
                        : 'No officers found for this role'}
                    </option>
                    {Array.isArray(systemRoles) &&
                      systemRoles
                        .filter((u: any) => u.role === assignedRole)
                        .map((u: any) => (
                          <option key={u.id} value={u.id}>
                            {u.firstName} {u.lastName} ({u.email})
                          </option>
                        ))}
                  </select>
                </div>
              </div>
            </div>
          ) : (
            <div className="p-3.5 rounded-xl border border-border/30 bg-muted/10 space-y-3">
              <div className="flex items-center gap-2 text-foreground">
                <Upload className="h-4 w-4 text-primary" />
                <span className="text-xs font-bold uppercase tracking-wider">
                  KYC Document File Uploads
                </span>
              </div>

              <div className="space-y-3">
                {documentFields.map((field, index) => (
                  <div
                    key={field.id}
                    className="flex items-end gap-2 bg-background p-3 rounded-lg border border-border/30"
                  >
                    <div className="w-1/3">
                      <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                        Document Type
                      </label>
                      <select
                        {...register(`kyc.documents.${index}.type` as const)}
                        className="w-full text-xs p-2 border border-border/40 rounded-lg bg-background text-foreground focus:outline-none focus:border-primary"
                      >
                        {DOCUMENT_TYPES.map((dt) => (
                          <option key={dt.value} value={dt.value}>
                            {dt.label}
                          </option>
                        ))}
                      </select>
                    </div>

                    <div className="w-2/3">
                      <label className="block text-[10px] font-bold uppercase text-muted-foreground/80 mb-1">
                        Select File
                      </label>
                      <Controller
                        control={control}
                        name={`kyc.documents.${index}.file` as const}
                        render={({ field: { onChange } }) => (
                          <input
                            type="file"
                            accept=".pdf,.png,.jpg,.jpeg"
                            onChange={(e) =>
                              onChange(e.target.files?.[0] || null)
                            }
                            className="w-full text-xs text-muted-foreground file:mr-2 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:text-[10px] file:font-bold file:bg-primary/10 file:text-primary hover:file:bg-primary/20"
                          />
                        )}
                      />
                    </div>

                    {documentFields.length > 1 && (
                      <button
                        type="button"
                        onClick={() => removeDocument(index)}
                        className="text-muted-foreground hover:text-destructive p-2 rounded-lg hover:bg-destructive/10"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    )}
                  </div>
                ))}
              </div>

              <Button
                type="button"
                variant="outline"
                onClick={() => appendDocument({ type: 'OTHER', file: null })}
                className="h-8 text-[10px] gap-1 font-bold border-dashed w-full mt-1"
              >
                <Plus className="h-3 w-3" /> Attach Additional KYC Document File
              </Button>
            </div>
          )}
        </div>

        {/* STICKY FOOTER */}
        <div className="sticky bottom-0 w-full bg-surface border border-border/40 py-4 px-6 z-40 flex items-center justify-end gap-3 shadow-xl rounded-xl">
          <Button
            type="button"
            variant="ghost"
            onClick={() => router.back()}
            className="h-9 text-xs font-semibold"
          >
            Discard Parameters
          </Button>
          <Button
            type="submit"
            disabled={provisionMutation.isPending}
            className="h-9 rounded-lg px-4 text-xs font-semibold bg-primary text-primary-foreground gap-1.5 shadow-sm"
          >
            <Check className="h-4 w-4 stroke-[2.5]" />
            <span>
              {provisionMutation.isPending
                ? 'Provisioning Institute Node...'
                : 'Deploy Campus & Provision Admin'}
            </span>
          </Button>
        </div>
      </form>
    </div>
  );
}