'use client';

import { useState, useRef } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { useForm } from 'react-hook-form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
  useSendAdvisorOtp,
  useVerifyAdvisorOtp,
  useRegisterAdvisor,
  useUploadAdvisorDocument,
} from '@/services/advisor-onboarding/queries';
import { useAllDistricts } from '@/services/districts/queries';
import { useAllSectors } from '@/services/sectors/queries';
import { useInstitutesBySector } from '@/services/institutes/queries';
import { DOCUMENT_TYPES } from '@/constants/documents';

type DocumentTypeValue = (typeof DOCUMENT_TYPES)[number]['value'];

interface RegistrationFormData {
  name: string;
  email: string;
  dob: string;
  gender: 'MALE' | 'FEMALE' | 'OTHER';
  experienceYears: number;
  qualification: string;
  address: string;
  bankAccountNumber: string;
  bankIFSC: string;
  bankName: string;
  bankAccountHolder: string;
  password: string;
  instituteId: string;
}

interface UploadedDocumentItem {
  type: DocumentTypeValue;
  fileUrl: string;
  fileName: string;
}

export default function AdvisorRegisterPage() {
  const router = useRouter();
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  const [step, setStep] = useState<'PHONE_OTP' | 'PROFILE_FORM' | 'DOCUMENTS_UPLOAD'>('PHONE_OTP');

  // Auth Context State
  const [phone, setPhone] = useState('');
  const [otpCode, setOtpCode] = useState('');
  const [otpSent, setOtpSent] = useState(false);
  const [registrationToken, setRegistrationToken] = useState('');

  // Step 3 Document Upload State
  const [documents, setDocuments] = useState<UploadedDocumentItem[]>([]);
  const [currentDocType, setCurrentDocType] = useState<DocumentTypeValue>(DOCUMENT_TYPES[0].value);
  const [isDragging, setIsDragging] = useState(false);

  // Cascading Dropdowns State
  const [selectedDistrictId, setSelectedDistrictId] = useState('');
  const [selectedSectorId, setSelectedSectorId] = useState('');
  const [selectedInstituteId, setSelectedInstituteId] = useState('');

  // Queries
  const { data: districtsData, isLoading: isLoadingDistricts } = useAllDistricts();
  const rawDistricts = (districtsData as any)?.items || districtsData || [];

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

  const { data: institutesData, isLoading: isLoadingInstitutes } =
    useInstitutesBySector(selectedSectorId);
  const rawInstitutes = (institutesData as any)?.items || institutesData || [];

  // Mutations
  const sendOtpMutation = useSendAdvisorOtp();
  const verifyOtpMutation = useVerifyAdvisorOtp();
  const registerAdvisorMutation = useRegisterAdvisor();
  const uploadDocMutation = useUploadAdvisorDocument();

  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<RegistrationFormData>();

  // Handlers for Step 1
  const handleSendOtp = () => {
    if (!/^[6-9]\d{9}$/.test(phone)) {
      alert('Please enter a valid 10-digit Indian mobile number');
      return;
    }
    sendOtpMutation.mutate(phone, {
      onSuccess: () => setOtpSent(true),
    });
  };

  const handleVerifyOtp = () => {
    if (!otpCode || otpCode.length < 6) {
      alert('Please enter a valid 6-digit verification code.');
      return;
    }
    verifyOtpMutation.mutate(
      { phone, code: otpCode },
      {
        onSuccess: (res: any) => {
          setRegistrationToken(res.data.registrationToken);
          
          // Auto-resume to Step 3 if profile was already saved in database
          if (res.data.resumeStep === 'DOCUMENTS_UPLOAD') {
            setStep('DOCUMENTS_UPLOAD');
          } else {
            setStep('PROFILE_FORM');
          }
        },
      }
    );
  };

  // Dropdown cascades
  const handleDistrictChange = (districtId: string) => {
    setSelectedDistrictId(districtId);
    setSelectedSectorId('');
    setSelectedInstituteId('');
    setValue('instituteId', '', { shouldValidate: true });
  };

  const handleSectorChange = (sectorId: string) => {
    setSelectedSectorId(sectorId);
    setSelectedInstituteId('');
    setValue('instituteId', '', { shouldValidate: true });
  };

  const handleInstituteChange = (instituteId: string) => {
    setSelectedInstituteId(instituteId);
    setValue('instituteId', instituteId, { shouldValidate: true });
  };

  // Handlers for Step 2
  const onProfileSubmit = (data: RegistrationFormData) => {
    if (!selectedInstituteId) {
      alert('Please select an institute to complete registration.');
      return;
    }

    const payload = {
      ...data,
      instituteId: selectedInstituteId,
      phone,
      experienceYears: Number(data.experienceYears || 0),
      dob: new Date(data.dob).toISOString(),
    };

    registerAdvisorMutation.mutate(
      { payload, token: registrationToken },
      {
        onSuccess: () => {
          setStep('DOCUMENTS_UPLOAD');
        },
      }
    );
  };

  // Drag & Drop Box File Handlers
  const handleFileProcess = (file: File) => {
    // In production, integrate your cloud uploader (e.g., S3/UploadThing) to resolve a real URL
    const fileUrl = URL.createObjectURL(file);
    const fileName = file.name;

    const filtered = documents.filter((d) => d.type !== currentDocType);
    setDocuments([...filtered, { type: currentDocType, fileUrl, fileName }]);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = () => {
    setIsDragging(false);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFileProcess(e.dataTransfer.files[0]);
    }
  };

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      handleFileProcess(e.target.files[0]);
    }
  };

  const handleRemoveDocument = (docType: DocumentTypeValue) => {
    setDocuments(documents.filter((d) => d.type !== docType));
  };

  const handleFinalSubmit = () => {
    if (documents.length === 0) {
      alert('Please attach at least one verification document to complete onboarding.');
      return;
    }

    const payloadDocs = documents.map((doc) => ({
      type: doc.type,
      fileUrl: doc.fileUrl,
    }));

    uploadDocMutation.mutate(
      { documents: payloadDocs, token: registrationToken },
      {
        onSuccess: () => {
          router.push('/signin?message=Registration+Completed+Awaiting+Verification');
        },
      }
    );
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-muted/30 px-4 py-10">
      <div className="w-full max-w-2xl rounded-2xl border border-border/80 bg-card p-6 shadow-sm sm:p-8">
        
        {/* STEP PROGRESS INDICATOR */}
        <div className="mb-8">
          <div className="flex items-center justify-between text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-3">
            <span className={step === 'PHONE_OTP' ? 'text-primary font-bold' : ''}>
              1. Verification
            </span>
            <span className={step === 'PROFILE_FORM' ? 'text-primary font-bold' : ''}>
              2. Profile & Institution
            </span>
            <span className={step === 'DOCUMENTS_UPLOAD' ? 'text-primary font-bold' : ''}>
              3. Documents
            </span>
          </div>
          <div className="h-1.5 w-full rounded-full bg-muted overflow-hidden">
            <div
              className="h-full bg-primary transition-all duration-300 ease-out"
              style={{
                width:
                  step === 'PHONE_OTP'
                    ? '33%'
                    : step === 'PROFILE_FORM'
                    ? '66%'
                    : '100%',
              }}
            />
          </div>
        </div>

        {/* HEADER */}
        <div className="mb-6">
          <h1 className="text-2xl font-bold tracking-tight text-foreground">
            Career Advisor Onboarding
          </h1>
          <p className="mt-1 text-sm text-muted-foreground">
            {step === 'PHONE_OTP' && 'Verify your mobile number via OTP.'}
            {step === 'PROFILE_FORM' && 'Complete your personal, institutional, and payout details.'}
            {step === 'DOCUMENTS_UPLOAD' && 'Upload mandatory verification documents to complete registration.'}
          </p>
        </div>

        {/* STEP 1: OTP */}
        {step === 'PHONE_OTP' && (
          <div className="space-y-4">
            <div>
              <label className="mb-1.5 block text-sm font-medium text-foreground">
                Mobile Number
              </label>
              <div className="flex gap-2">
                <Input
                  type="tel"
                  placeholder="xxxxx xxxxx"
                  value={phone}
                  disabled={otpSent}
                  onChange={(e) => setPhone(e.target.value)}
                  className="flex-1"
                />
                <Button
                  type="button"
                  variant={otpSent ? 'outline' : 'primary'}
                  onClick={handleSendOtp}
                  className='text-[10px]'
                  isLoading={sendOtpMutation.isPending}
                >
                  {otpSent ? 'Resend OTP' : 'Send OTP'}
                </Button>
              </div>
            </div>

            {otpSent && (
              <div className="space-y-4 pt-3 border-t border-border/60">
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-foreground">
                    Enter 6-Digit Verification Code
                  </label>
                  <Input
                    type="text"
                    maxLength={6}
                    placeholder="123456"
                    value={otpCode}
                    onChange={(e) => setOtpCode(e.target.value)}
                  />
                </div>
                <Button
                  type="button"
                  className="w-full"
                  onClick={handleVerifyOtp}
                  isLoading={verifyOtpMutation.isPending}
                >
                  Verify Code & Continue
                </Button>
              </div>
            )}
          </div>
        )}

        {/* STEP 2: PROFILE FORM */}
        {step === 'PROFILE_FORM' && (
          <form onSubmit={handleSubmit(onProfileSubmit)} className="space-y-6">
            
            {/* JURISDICTION ASSIGNMENT */}
            <div className="rounded-xl border border-border bg-muted/30 p-4 space-y-3">
              <h2 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                Institutional Assignment
              </h2>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                <div>
                  <label className="block text-xs font-medium text-foreground mb-1">
                    District {isLoadingDistricts && <span className="text-primary text-[10px] animate-pulse">(loading...)</span>}
                  </label>
                  <select
                    value={selectedDistrictId}
                    onChange={(e) => handleDistrictChange(e.target.value)}
                    className="w-full text-sm h-10 px-3 border border-input rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring cursor-pointer"
                  >
                    <option value="">Select District</option>
                    {rawDistricts.map((d: any) => (
                      <option key={d.id} value={d.id}>
                        {d.name}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-xs font-medium text-foreground mb-1">
                    Sector {isLoadingSectors && <span className="text-primary text-[10px] animate-pulse">(loading...)</span>}
                  </label>
                  <select
                    value={selectedSectorId}
                    onChange={(e) => handleSectorChange(e.target.value)}
                    disabled={!selectedDistrictId || rawSectors.length === 0}
                    className="w-full text-sm h-10 px-3 border border-input rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring cursor-pointer disabled:opacity-50"
                  >
                    <option value="">
                      {!selectedDistrictId
                        ? 'Select District First'
                        : rawSectors.length === 0
                        ? 'No sectors available'
                        : 'Select Sector'}
                    </option>
                    {rawSectors.map((s: any) => (
                      <option key={s.id} value={s.id}>
                        {s.name}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-xs font-medium text-foreground mb-1">
                    Institute {isLoadingInstitutes && <span className="text-primary text-[10px] animate-pulse">(loading...)</span>}
                  </label>
                  <select
                    value={selectedInstituteId}
                    onChange={(e) => handleInstituteChange(e.target.value)}
                    disabled={!selectedSectorId || rawInstitutes.length === 0}
                    className="w-full text-sm h-10 px-3 border border-input rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring cursor-pointer disabled:opacity-50"
                  >
                    <option value="">
                      {!selectedSectorId
                        ? 'Select Sector First'
                        : rawInstitutes.length === 0
                        ? 'No institutes mapped'
                        : 'Select Institute'}
                    </option>
                    {rawInstitutes.map((inst: any) => (
                      <option key={inst.id} value={inst.id}>
                        {inst.name} {inst.code ? `(${inst.code})` : ''}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              <input type="hidden" {...register('instituteId', { required: 'Please select an institute' })} />
              {errors.instituteId && (
                <p className="text-xs text-destructive mt-1 font-medium">{errors.instituteId.message}</p>
              )}
            </div>

            {/* PERSONAL DETAILS */}
            <div className="space-y-4">
              <h2 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                Personal Information
              </h2>
              
              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div>
                  <label className="mb-1 block text-sm font-medium text-foreground">Full Name</label>
                  <Input {...register('name', { required: 'Full Name is required' })} placeholder="John Doe" />
                  {errors.name && <p className="text-xs text-destructive mt-1">{errors.name.message}</p>}
                </div>

                <div>
                  <label className="mb-1 block text-sm font-medium text-foreground">Email Address</label>
                  <Input
                    type="email"
                    {...register('email', {
                      required: 'Email address is required',
                      pattern: { value: /^\S+@\S+$/i, message: 'Invalid email address' },
                    })}
                    placeholder="john@example.com"
                  />
                  {errors.email && <p className="text-xs text-destructive mt-1">{errors.email.message}</p>}
                </div>

                <div>
                  <label className="mb-1 block text-sm font-medium text-foreground">Date of Birth</label>
                  <Input type="date" {...register('dob', { required: 'Date of Birth is required' })} />
                  {errors.dob && <p className="text-xs text-destructive mt-1">{errors.dob.message}</p>}
                </div>

                <div>
                  <label className="mb-1 block text-sm font-medium text-foreground">Gender</label>
                  <select
                    {...register('gender', { required: 'Gender is required' })}
                    className="w-full h-10 px-3 text-sm rounded-md border border-input bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring"
                  >
                    <option value="MALE">Male</option>
                    <option value="FEMALE">Female</option>
                    <option value="OTHER">Other</option>
                  </select>
                </div>

                <div>
                  <label className="mb-1 block text-sm font-medium text-foreground">Experience (Years)</label>
                  <Input type="number" min={0} {...register('experienceYears')} defaultValue={0} />
                </div>

                <div>
                  <label className="mb-1 block text-sm font-medium text-foreground">Highest Qualification</label>
                  <Input
                    {...register('qualification', { required: 'Qualification is required' })}
                    placeholder="B.Tech / M.Sc / B.Ed"
                  />
                  {errors.qualification && <p className="text-xs text-destructive mt-1">{errors.qualification.message}</p>}
                </div>
              </div>

              <div>
                <label className="mb-1 block text-sm font-medium text-foreground">Residential Address</label>
                <Input {...register('address', { required: 'Address is required' })} placeholder="Full residential address" />
                {errors.address && <p className="text-xs text-destructive mt-1">{errors.address.message}</p>}
              </div>
            </div>

            {/* BANK DETAILS */}
            <div className="rounded-xl border border-border bg-muted/20 p-4 space-y-4">
              <h2 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                Bank Account Details (Payouts)
              </h2>

              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div>
                  <label className="mb-1 block text-xs font-medium text-foreground">Account Holder Name</label>
                  <Input {...register('bankAccountHolder', { required: 'Account holder name is required' })} placeholder="John Doe" />
                  {errors.bankAccountHolder && <p className="text-xs text-destructive mt-1">{errors.bankAccountHolder.message}</p>}
                </div>

                <div>
                  <label className="mb-1 block text-xs font-medium text-foreground">Account Number</label>
                  <Input {...register('bankAccountNumber', { required: 'Account number is required' })} placeholder="1234567890" />
                  {errors.bankAccountNumber && <p className="text-xs text-destructive mt-1">{errors.bankAccountNumber.message}</p>}
                </div>

                <div>
                  <label className="mb-1 block text-xs font-medium text-foreground">IFSC Code</label>
                  <Input
                    {...register('bankIFSC', {
                      required: 'IFSC Code is required',
                      setValueAs: (v) => v.toUpperCase().trim(),
                    })}
                    maxLength={11}
                    placeholder="SBIN0001234"
                  />
                  {errors.bankIFSC && <p className="text-xs text-destructive mt-1">{errors.bankIFSC.message}</p>}
                </div>

                <div>
                  <label className="mb-1 block text-xs font-medium text-foreground">Bank Name</label>
                  <Input {...register('bankName', { required: 'Bank name is required' })} placeholder="State Bank of India" />
                  {errors.bankName && <p className="text-xs text-destructive mt-1">{errors.bankName.message}</p>}
                </div>
              </div>
            </div>

            {/* SECURITY */}
            <div>
              <label className="mb-1 block text-sm font-medium text-foreground">Account Password</label>
              <Input
                type="password"
                {...register('password', {
                  required: 'Password is required',
                  minLength: { value: 8, message: 'Password must be at least 8 characters' },
                })}
                placeholder="••••••••"
              />
              {errors.password && <p className="text-xs text-destructive mt-1">{errors.password.message}</p>}
            </div>

            <Button
              type="submit"
              className="w-full"
              isLoading={registerAdvisorMutation.isPending}
              disabled={!selectedInstituteId}
            >
              Save Profile & Proceed to Documents
            </Button>
          </form>
        )}

        {/* STEP 3: DOCUMENT UPLOADS WITH DROP BOX */}
        {step === 'DOCUMENTS_UPLOAD' && (
          <div className="space-y-6">
            <div className="rounded-xl border border-border bg-muted/20 p-4 space-y-4">
              <h2 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                Attach Verification Documents
              </h2>

              <div>
                <label className="block text-xs font-medium text-foreground mb-1">
                  Target Document Category
                </label>
                <select
                  value={currentDocType}
                  onChange={(e) => setCurrentDocType(e.target.value as DocumentTypeValue)}
                  className="w-full text-sm h-10 px-3 border border-input rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring cursor-pointer"
                >
                  {DOCUMENT_TYPES.map((doc) => (
                    <option key={doc.value} value={doc.value}>
                      {doc.label}
                    </option>
                  ))}
                </select>
              </div>

              {/* DRAG AND DROP BOX */}
              <div
                onDragOver={handleDragOver}
                onDragLeave={handleDragLeave}
                onDrop={handleDrop}
                onClick={() => fileInputRef.current?.click()}
                className={`flex flex-col items-center justify-center p-6 border-2 border-dashed rounded-xl cursor-pointer transition-colors ${
                  isDragging
                    ? 'border-primary bg-primary/5'
                    : 'border-border bg-background hover:bg-muted/30'
                }`}
              >
                <input
                  type="file"
                  ref={fileInputRef}
                  onChange={handleFileSelect}
                  className="hidden"
                  accept="image/*,application/pdf"
                />
                <div className="p-3 rounded-full bg-primary/10 text-primary mb-2">
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M7 16a4 4 0 01-.88-7.903A5 4 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                  </svg>
                </div>
                <p className="text-xs font-semibold text-foreground">
                  Drag and drop document here, or <span className="text-primary hover:underline">browse</span>
                </p>
                <p className="text-[10px] text-muted-foreground mt-1">
                  Supports PDF, PNG, JPG (Max 5MB)
                </p>
              </div>
            </div>

            {/* ATTACHED DOCUMENTS LIST */}
            <div className="space-y-2">
              <h3 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                Attached Documents ({documents.length})
              </h3>

              {documents.length === 0 ? (
                <div className="p-4 rounded-lg border border-dashed border-border text-center text-xs text-muted-foreground">
                  No documents attached yet. Drop files above to attach.
                </div>
              ) : (
                <div className="space-y-2">
                  {documents.map((doc) => {
                    const label = DOCUMENT_TYPES.find((d) => d.value === doc.type)?.label || doc.type;
                    return (
                      <div
                        key={doc.type}
                        className="flex items-center justify-between p-3 rounded-lg border border-border bg-card text-xs"
                      >
                        <div>
                          <div className="flex items-center gap-2">
                            <span className="font-semibold text-foreground">{label}</span>
                            <span className="text-[10px] bg-primary/10 text-primary px-1.5 py-0.5 rounded font-mono">
                              {doc.type}
                            </span>
                          </div>
                          <p className="text-muted-foreground text-[11px] truncate max-w-xs sm:max-w-md mt-0.5">
                            {doc.fileName}
                          </p>
                        </div>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => handleRemoveDocument(doc.type)}
                          className="text-destructive hover:text-destructive h-8 px-2 text-xs"
                        >
                          Remove
                        </Button>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>

            <Button
              type="button"
              className="w-full"
              onClick={handleFinalSubmit}
              isLoading={uploadDocMutation.isPending}
              disabled={documents.length === 0}
            >
              Complete Onboarding & Submit
            </Button>
          </div>
        )}

        {/* FOOTER */}
        <p className="mt-6 text-center text-sm text-muted-foreground">
          Already registered?{' '}
          <Link href="/signin" className="font-medium text-primary hover:underline">
            Sign in here
          </Link>
        </p>

      </div>
    </div>
  );
}