'use client';

import React, { useEffect, useState } from 'react';
import {
  X,
  User,
  GraduationCap,
  CreditCard,
  Building2,
  CheckCircle2,
  CheckCheck,
  MapPin,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { OnboardingStepper } from './OnboardingStepper';
import { PermissionGuard } from '@/features/auth/guards';
import { PERMISSIONS } from '@/constants/permissions';

interface AdvisorDetailsDrawerProps {
  advisor: {
    id: string;
    name?: string;
    email?: string;
    mobile?: string;
    dob?: string;
    gender?: string;
    address?: string;
    qualification?: string;
    experienceYears?: number;
    bankName?: string;
    bankAccountNumber?: string;
    bankIFSC?: string;
    bankAccountHolder?: string;
    status?: string;
    isActive?: boolean;
    institute?: {
      id: string;
      name: string;
      code: string;
    };
  };
  onClose: () => void;
  onVerify?: (advisorId: string) => void;
  onSectorApprove?: (advisorId: string) => void;
  isVerifying?: boolean;
}

export default function AdvisorDetailsDrawer({
  advisor,
  onClose,
  onVerify,
  onSectorApprove,
  isVerifying = false,
}: AdvisorDetailsDrawerProps) {
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = 'unset';
    };
  }, []);

  const handleSafeClose = () => {
    setIsMounted(false);
    setTimeout(() => {
      onClose();
    }, 250);
  };

  const nameStr = advisor.name?.trim() || '';
  const nameParts = nameStr ? nameStr.split(/\s+/) : [];
  let initials = 'CA';
  if (nameParts.length >= 2) {
    initials = `${nameParts[0]?.[0] ?? ''}${nameParts[nameParts.length - 1]?.[0] ?? ''}`;
  } else if (nameParts.length === 1 && nameParts[0]) {
    initials = nameParts[0].slice(0, 2);
  }

  return (
    <>
      {/* Backdrop Blur Overlay */}
      <div
        className={`fixed inset-0 bg-black/40 backdrop-blur-xs z-40 transition-opacity duration-300 ease-in-out ${
          isMounted ? 'opacity-100' : 'opacity-0'
        }`}
        onClick={handleSafeClose}
      />

      {/* Sliding Panel Container */}
      <div
        className={`fixed right-0 top-0 bottom-0 w-full max-w-2xl bg-background border-l border-border shadow-2xl z-50 p-6 flex flex-col justify-between transform transition-transform duration-300 ease-in-out ${
          isMounted ? 'translate-x-0' : 'translate-x-full'
        } select-none`}
      >
        {/* Main Scrolling Content Area */}
        <div className="space-y-6 flex-1 overflow-y-auto pr-1">
          {/* Drawer Header */}
          <div className="flex items-center justify-between border-b border-border/10 pb-4">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-xl bg-primary/10 border border-primary/20 flex items-center justify-center text-sm font-black text-primary uppercase shrink-0">
                {initials}
              </div>
              <div className="flex flex-col text-left">
                <h2 className="text-base font-bold text-foreground leading-tight">
                  {advisor.name ?? 'Advisor Profile'}
                </h2>
                <span className="text-[11px] text-muted-foreground font-mono">
                  ID: {advisor.id}
                </span>
              </div>
            </div>
            <button
              onClick={handleSafeClose}
              className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground/70 hover:text-foreground transition-colors cursor-pointer"
            >
              <X className="h-4 w-4" />
            </button>
          </div>

          {/* ONBOARDING STEPPER BOARD */}
          <div className="bg-muted/30 border border-border/40 rounded-xl p-4 text-left space-y-2">
            <div className="flex items-center justify-between">
              <span className="text-[10px] font-extrabold uppercase tracking-wider text-muted-foreground">
                Current Onboarding Lifecycle State
              </span>
              <span className="text-[10px] font-bold px-2 py-0.5 rounded-full bg-primary/10 text-primary border border-primary/20">
                {advisor.status?.replace(/_/g, ' ') || 'PENDING VERIFICATION'}
              </span>
            </div>
            <OnboardingStepper currentStatus={advisor.status || 'PENDING_VERIFICATION'} />
          </div>

          {/* PERSONAL & CONTACT INFORMATION */}
          <div className="border border-border/40 bg-surface/50 rounded-xl p-4 space-y-3 text-left shadow-xs">
            <div className="flex items-center gap-1.5 text-[10px] font-extrabold uppercase tracking-wider text-muted-foreground">
              <User className="h-3.5 w-3.5 text-primary" /> Personal & Contact Context
            </div>

            <div className="grid grid-cols-2 gap-x-4 gap-y-3 text-xs border-t border-border/10 pt-3">
              <div>
                <span className="text-[10px] block text-muted-foreground/70 font-medium">Full Name</span>
                <span className="font-semibold text-foreground">{advisor.name || '—'}</span>
              </div>

              <div>
                <span className="text-[10px] block text-muted-foreground/70 font-medium">Email Address</span>
                <span className="font-mono text-foreground/90 truncate block">{advisor.email || '—'}</span>
              </div>

              <div>
                <span className="text-[10px] block text-muted-foreground/70 font-medium">Mobile Phone</span>
                <span className="font-mono text-foreground">{advisor.mobile || '—'}</span>
              </div>

              <div>
                <span className="text-[10px] block text-muted-foreground/70 font-medium">Gender / DOB</span>
                <span className="font-medium text-foreground">
                  {advisor.gender || '—'} {advisor.dob ? `(${new Date(advisor.dob).toLocaleDateString()})` : ''}
                </span>
              </div>

              {advisor.address && (
                <div className="col-span-2">
                  <span className="text-[10px] block text-muted-foreground/70 font-medium flex items-center gap-1">
                    <MapPin className="h-3 w-3" /> Address
                  </span>
                  <span className="font-medium text-foreground leading-tight block">{advisor.address}</span>
                </div>
              )}
            </div>
          </div>

          {/* QUALIFICATION & JURISDICTION */}
          <div className="border border-border/40 bg-surface/50 rounded-xl p-4 space-y-3 text-left shadow-xs">
            <div className="flex items-center gap-1.5 text-[10px] font-extrabold uppercase tracking-wider text-muted-foreground">
              <GraduationCap className="h-3.5 w-3.5 text-primary" /> Professional & Institution Node
            </div>

            <div className="grid grid-cols-2 gap-x-4 gap-y-3 text-xs border-t border-border/10 pt-3">
              <div>
                <span className="text-[10px] block text-muted-foreground/70 font-medium">Highest Qualification</span>
                <span className="font-semibold text-foreground">{advisor.qualification || '—'}</span>
              </div>

              <div>
                <span className="text-[10px] block text-muted-foreground/70 font-medium">Field Experience</span>
                <span className="font-semibold text-foreground">{advisor.experienceYears ?? 0} Years</span>
              </div>

              {advisor.institute && (
                <div className="col-span-2">
                  <span className="text-[10px] block text-muted-foreground/70 font-medium flex items-center gap-1">
                    <Building2 className="h-3 w-3" /> Assigned Institute
                  </span>
                  <span className="font-bold text-foreground">
                    {advisor.institute.name} ({advisor.institute.code})
                  </span>
                </div>
              )}
            </div>
          </div>

          {/* SETTLEMENT BANK ACCOUNT DETAILS */}
          <div className="border border-border/40 bg-surface/50 rounded-xl p-4 space-y-3 text-left shadow-xs">
            <div className="flex items-center gap-1.5 text-[10px] font-extrabold uppercase tracking-wider text-muted-foreground">
              <CreditCard className="h-3.5 w-3.5 text-primary" /> Settlement Account Parameters
            </div>

            <div className="grid grid-cols-2 gap-x-4 gap-y-3 text-xs border-t border-border/10 pt-3">
              <div>
                <span className="text-[10px] block text-muted-foreground/70 font-medium">Bank Name</span>
                <span className="font-semibold text-foreground">{advisor.bankName || '—'}</span>
              </div>

              <div>
                <span className="text-[10px] block text-muted-foreground/70 font-medium">Account Holder</span>
                <span className="font-semibold text-foreground">{advisor.bankAccountHolder || advisor.name || '—'}</span>
              </div>

              <div>
                <span className="text-[10px] block text-muted-foreground/70 font-medium">Account Number</span>
                <span className="font-mono text-foreground font-bold">{advisor.bankAccountNumber || '—'}</span>
              </div>

              <div>
                <span className="text-[10px] block text-muted-foreground/70 font-medium">IFSC Code</span>
                <span className="font-mono text-foreground font-bold">{advisor.bankIFSC || '—'}</span>
              </div>
            </div>
          </div>
        </div>

        {/* Bottom Drawer Action Footer */}
        <div className="border-t border-border/10 pt-4 flex items-center justify-between">
          <Button variant="ghost" onClick={handleSafeClose} className="h-8 text-xs font-semibold cursor-pointer">
            Close Panel
          </Button>

          <div className="flex items-center gap-2">
            {/* Step 3: Institute Verification Action */}
            {advisor.status === 'PENDING_VERIFICATION' && onVerify && (
              <Button
                disabled={isVerifying}
                onClick={() => onVerify(advisor.id)}
                className="h-8 text-xs font-bold gap-1.5 rounded-lg bg-emerald-600 text-white hover:bg-emerald-700 cursor-pointer disabled:opacity-50"
              >
                <CheckCircle2 className="h-3.5 w-3.5 stroke-[2.5]" />
                <span>Institute Verify</span>
              </Button>
            )}

            {/* Step 4: Sector Approval Action */}
            {advisor.status === 'INSTITUTE_VERIFIED' && onSectorApprove && (
              <PermissionGuard permission={PERMISSIONS.ADVISORS_READ}>
                <Button
                  disabled={isVerifying}
                  onClick={() => onSectorApprove(advisor.id)}
                  className="h-8 text-xs font-bold gap-1.5 rounded-lg bg-indigo-600 text-white hover:bg-indigo-700 cursor-pointer disabled:opacity-50"
                >
                  <CheckCheck className="h-3.5 w-3.5 stroke-[2.5]" />
                  <span>Sector Approve</span>
                </Button>
              </PermissionGuard>
            )}
          </div>
        </div>
      </div>
    </>
  );
}