'use client';

import React, { useState } from 'react';
import {
  CheckCircle2,
  Clock,
  Plus,
  Search,
  ShieldCheck,
  Eye,
  CheckCheck,
  ArrowRight,
  ShieldAlert,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { DataTable, Column } from '@/components/ui/data-table';
import { TableSkeleton } from '@/components/ui/tableSkeleton';
import {
  useCareerAdvisors,
  useVerifyCareerAdvisor,
  useApproveSectorAdvisor,
} from '@/services/advisor-onboarding/queries';
import AdvisorDetailsDrawer from './_components/AdvisorDetailsDrawer';
import { useAuthorization } from '@/features/auth/guards';

interface CareerAdvisorRow {
  id: string;
  name?: string;
  email?: string;
  mobile?: string;
  qualification?: string;
  experienceYears?: number;
  bankName?: string;
  bankAccountNumber?: string;
  bankIFSC?: string;
  status?: string;
  isActive?: boolean;
  institute?: {
    id: string;
    name: string;
    code: string;
  };
}

export default function CareerAdvisorsPage() {
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [page, setPage] = useState(1);

  // User Auth context to inspect current user role
  const { user } = useAuthorization();
  const userRole = user?.role; // e.g., 'INSTITUTE_ADMIN', 'DISTRICT_SECTOR_OWNER', 'STATE_OWNER', 'SUPER_ADMIN'

  // Drawer state
  const [selectedAdvisor, setSelectedAdvisor] = useState<CareerAdvisorRow | null>(null);

  // Server queries & mutation hooks
  const { data, isLoading, isFetching } = useCareerAdvisors(page, search, statusFilter);
  const verifyAdvisorMutation = useVerifyCareerAdvisor();
  const approveSectorMutation = useApproveSectorAdvisor();

  const advisorsList: CareerAdvisorRow[] = data?.items || [];

  const columns: Column<CareerAdvisorRow>[] = [
    {
      header: 'Governance Profile Node',
      cell: (row) => {
        const nameStr = row.name?.trim() || '';
        const nameParts = nameStr ? nameStr.split(/\s+/) : [];

        let initials = 'CA';
        if (nameParts.length >= 2) {
          const firstLetter = nameParts[0]?.[0] ?? '';
          const lastLetter = nameParts[nameParts.length - 1]?.[0] ?? '';
          initials = `${firstLetter}${lastLetter}` || 'CA';
        } else if (nameParts.length === 1 && nameParts[0]) {
          initials = nameParts[0].slice(0, 2);
        }

        return (
          <div
            onClick={() => setSelectedAdvisor(row)}
            className="flex items-center gap-3 text-left cursor-pointer group"
          >
            <div className="h-8 w-8 rounded-lg bg-primary/10 border border-primary/20 flex items-center justify-center text-xs font-bold text-primary shrink-0 uppercase group-hover:bg-primary group-hover:text-white transition-colors">
              {initials}
            </div>
            <div className="flex flex-col">
              <span className="font-semibold text-foreground text-xs leading-tight group-hover:text-primary transition-colors">
                {row.name ?? 'N/A'}
              </span>
              <span className="text-[10px] text-muted-foreground/70 font-mono mt-0.5">
                {row.email ?? 'N/A'} • {row.mobile ?? 'N/A'}
              </span>
            </div>
          </div>
        );
      },
    },
    {
      header: 'Qualifications & Credentialing',
      cell: (row) => (
        <div className="flex flex-col text-left">
          <span className="font-semibold text-foreground text-xs leading-tight">
            {row.qualification ?? 'N/A'}
          </span>
          <span className="text-[10px] text-muted-foreground/70 mt-0.5">
            {row.experienceYears ?? 0} Years Industry Field Experience
          </span>
        </div>
      ),
    },
    {
      header: 'Settlement Account Details',
      cell: (row) => (
        <div className="flex flex-col text-left">
          <span className="font-semibold text-foreground text-xs leading-tight">
            {row.bankName ?? 'N/A'}
          </span>
          <span className="text-[10px] text-muted-foreground/70 font-mono mt-0.5">
            A/C: {row.bankAccountNumber ?? 'N/A'} • IFSC: {row.bankIFSC ?? 'N/A'}
          </span>
        </div>
      ),
    },
    {
      header: 'Verification Stage',
      className: 'w-44',
      cell: (row) => {
        const status = row.status || 'PENDING';

        if (status === 'ACTIVE' || row.isActive) {
          return (
            <span className="inline-flex items-center gap-1 px-2.5 py-1 text-[10px] font-bold rounded-full bg-emerald-500/10 text-emerald-600 border border-emerald-500/20">
              <ShieldCheck className="h-3 w-3" /> Operational
            </span>
          );
        }

        if (status === 'DOCUMENTS_SUBMITTED' || status === 'PENDING_VERIFICATION') {
          return (
            <span className="inline-flex items-center gap-1 px-2.5 py-1 text-[10px] font-bold rounded-full bg-amber-500/10 text-amber-600 border border-amber-500/20">
              <Clock className="h-3 w-3" /> Awaiting Institute Review
            </span>
          );
        }

        if (status === 'INSTITUTE_VERIFIED') {
          return (
            <span className="inline-flex items-center gap-1 px-2.5 py-1 text-[10px] font-bold rounded-full bg-indigo-500/10 text-indigo-600 border border-indigo-500/20">
              <Clock className="h-3 w-3" /> Awaiting Sector Approval
            </span>
          );
        }

        if (status === 'SECTOR_APPROVED') {
          return (
            <span className="inline-flex items-center gap-1 px-2.5 py-1 text-[10px] font-bold rounded-full bg-sky-500/10 text-sky-600 border border-sky-500/20">
              <CheckCircle2 className="h-3 w-3" /> Training & Orientation
            </span>
          );
        }

        return (
          <span className="inline-flex items-center gap-1 px-2.5 py-1 text-[10px] font-bold rounded-full bg-muted/40 text-muted-foreground border border-border/40">
            <Clock className="h-3 w-3" /> {status.replace(/_/g, ' ')}
          </span>
        );
      },
    },
    {
      header: 'Profile Details',
      className: 'text-center w-24',
      cell: (row) => (
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setSelectedAdvisor(row)}
          className="h-7 text-[10px] font-bold rounded-md px-2 gap-1 text-muted-foreground hover:text-foreground cursor-pointer"
        >
          <Eye className="h-3.5 w-3.5" />
          <span>View</span>
        </Button>
      ),
    },
    /* DYNAMIC MATRIX CONTROLS COLUMN */
    {
      header: 'Required Action',
      className: 'text-right w-48',
      cell: (row) => {
        const isInstituteAdmin = userRole === 'INSTITUTE_ADMIN';
        const isDsoOrState =
          userRole === 'DISTRICT_SECTOR_OWNER' ||
          userRole === 'DISTRICT_OWNER' ||
          userRole === 'STATE_OWNER' ||
          userRole === 'SUPER_ADMIN';

        const status = row.status;

        // 1. Action for Institute Admin when advisor has submitted docs
        if (
          isInstituteAdmin &&
          (status === 'DOCUMENTS_SUBMITTED' || status === 'PENDING_VERIFICATION')
        ) {
          return (
            <Button
              size="sm"
              disabled={verifyAdvisorMutation.isPending}
              onClick={() => verifyAdvisorMutation.mutate(row.id)}
              className="h-8 text-[11px] font-bold rounded-lg px-3 gap-1.5 bg-emerald-600 text-white hover:bg-emerald-700 shadow-xs cursor-pointer"
            >
              <CheckCircle2 className="h-3.5 w-3.5" />
              <span>Verify Advisor</span>
            </Button>
          );
        }

        // 2. Action for DSO / State Owner when Institute has verified
        if (isDsoOrState && status === 'INSTITUTE_VERIFIED') {
          return (
            <Button
              size="sm"
              disabled={approveSectorMutation.isPending}
              onClick={() => approveSectorMutation.mutate(row.id)}
              className="h-8 text-[11px] font-bold rounded-lg px-3 gap-1.5 bg-indigo-600 text-white hover:bg-indigo-700 shadow-xs cursor-pointer animate-pulse"
            >
              <CheckCheck className="h-3.5 w-3.5" />
              <span>Approve Sector</span>
            </Button>
          );
        }

        // 3. Informational State: Institute Admin already verified, waiting for DSO
        if (isInstituteAdmin && status === 'INSTITUTE_VERIFIED') {
          return (
            <div className="flex items-center justify-end gap-1 text-[10px] font-bold text-indigo-600 bg-indigo-50 px-2.5 py-1 rounded-md border border-indigo-100">
              <span>Verified • Pending DSO</span>
              <ArrowRight className="h-3 w-3" />
            </div>
          );
        }

        // 4. Informational State: DSO seeing advisor before Institute Admin verified
        if (
          isDsoOrState &&
          (status === 'DOCUMENTS_SUBMITTED' || status === 'PENDING_VERIFICATION')
        ) {
          return (
            <span className="text-[10px] font-medium text-muted-foreground/80 italic">
              Awaiting Institute Verification
            </span>
          );
        }

        // 5. Approved / Completed Stage
        if (status === 'SECTOR_APPROVED' || status === 'ACTIVE' || row.isActive) {
          return (
            <div className="flex items-center justify-end gap-1 text-[10px] font-bold text-emerald-600">
              <ShieldCheck className="h-3.5 w-3.5" />
              <span>Approved</span>
            </div>
          );
        }

        // Default view for read-only / completed stages
        return (
          <span className="text-[10px] font-medium text-muted-foreground/60">
            No pending action
          </span>
        );
      },
    },
  ];

  return (
    <div className="space-y-4 max-w-7xl mx-auto animate-in fade-in duration-300 select-none">
      {/* Header */}
      <div className="flex items-center justify-between border-b border-border/10 pb-4">
        <div className="space-y-0.5">
          <h1 className="text-sm font-black tracking-widest text-foreground uppercase">
            Center Operations Desk
          </h1>
          <p className="text-[11px] font-medium text-muted-foreground/70">
            Physical facility local operations engine workspace and staff verification controls.
          </p>
        </div>

        <Button className="h-8 rounded-md px-3 text-[11px] font-bold tracking-wider uppercase shadow-xs gap-1.5 transition-all bg-foreground text-background hover:bg-foreground/90 cursor-pointer">
          <Plus className="h-3.5 w-3.5 stroke-[2.5]" /> Add Field Advisor
        </Button>
      </div>

      {/* Search and Filters */}
      <div className="flex flex-wrap items-center gap-2">
        <div className="flex items-center max-w-xs w-full relative group">
          <Search className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground/60 transition-colors group-focus-within:text-primary" />
          <input
            type="text"
            placeholder="Search advisors by name, email, phone..."
            value={search}
            onChange={(e) => {
              setSearch(e.target.value);
              setPage(1);
            }}
            className="w-full text-xs font-medium pl-8 pr-8 py-2 border border-border/40 bg-surface rounded-lg text-foreground focus:outline-none focus:border-primary transition-colors"
          />
          {isFetching && (
            <span className="absolute right-3 top-2.5 flex h-2 w-2">
              <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"></span>
              <span className="relative inline-flex rounded-full h-2 w-2 bg-primary"></span>
            </span>
          )}
        </div>

        <div className="w-full sm:w-auto">
          <select
            value={statusFilter}
            onChange={(e) => {
              setStatusFilter(e.target.value);
              setPage(1);
            }}
            className="w-full sm:w-auto text-xs font-semibold px-2.5 py-2 border border-border/40 bg-surface rounded-lg text-muted-foreground focus:outline-none focus:border-primary transition-colors cursor-pointer"
          >
            <option value="">All Onboarding Stages</option>
            <option value="PENDING_VERIFICATION">Step 1: Pending Verification</option>
            <option value="DOCUMENTS_SUBMITTED">Step 2: Documents Submitted</option>
            <option value="INSTITUTE_VERIFIED">Step 3: Institute Verified</option>
            <option value="SECTOR_APPROVED">Step 4: Sector Approved</option>
            <option value="ORIENTATION_COMPLETED">Step 5: Orientation Completed</option>
            <option value="TRAINING_COMPLETED">Step 6: Training Completed</option>
            <option value="CERTIFIED">Step 7: Certified</option>
            <option value="AGREEMENT_ACCEPTED">Step 8: Agreement Accepted</option>
            <option value="ACTIVE">Step 9: Active & Operational</option>
          </select>
        </div>
      </div>

      {/* Data Table */}
      {isLoading && !data ? (
        <TableSkeleton />
      ) : (
        <DataTable
          data={advisorsList}
          columns={columns}
          emptyMessage="No administrative advisor profile nodes registered matching criteria."
          pagination={
            data
              ? {
                  page: data.page,
                  pages: data.pages,
                  total: data.total,
                  onPageChange: setPage,
                }
              : undefined
          }
        />
      )}

      {/* SLIDING DETAILS DRAWER MOUNT */}
      {selectedAdvisor && (
        <AdvisorDetailsDrawer
          advisor={selectedAdvisor}
          onClose={() => setSelectedAdvisor(null)}
          onVerify={(advisorId) => {
            verifyAdvisorMutation.mutate(advisorId, {
              onSuccess: () => setSelectedAdvisor(null),
            });
          }}
          onSectorApprove={(advisorId) => {
            approveSectorMutation.mutate(advisorId, {
              onSuccess: () => setSelectedAdvisor(null),
            });
          }}
          isVerifying={verifyAdvisorMutation.isPending || approveSectorMutation.isPending}
        />
      )}
    </div>
  );
}