'use client';

import React, { useMemo, useState } from 'react';
import {
  Search,
  CheckCircle2,
  XCircle,
  Clock,
  Shield,
  ChevronRight,
  Filter,
  UserCheck,
  Layers,
  Home,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { DataTable, Column } from '@/components/ui/data-table';
import { TableSkeleton } from '@/components/ui/tableSkeleton';
import { usePendingApprovals } from '@/services/users/queries';
import { UserPendingApprovalRecord } from '@/services/users/types';
import { useReviewSectorKyc } from '@/services/sectorKyc/queries';
import { useReviewInstituteKyc } from '@/services/instituteKyc/queries';
import UserManagementDrawer from '../users/_components/UserManagementDrawer';
import PendingApprovalManagementDrawer from '../users/_components/PendingApprovalManagemantDrawer';

/**
 * A single row in the unified table. One user can produce multiple rows —
 * one for their personal KYC (if pending) and one per pending sector /
 * institute agreement request.
 */
type UnifiedKycType = 'PERSONAL' | 'SECTOR' | 'INSTITUTE';

interface UnifiedKycRow {
  key: string;
  type: UnifiedKycType;
  user: UserPendingApprovalRecord;
  requestId?: string; // sectorKycRequest.id / instituteKycRequest.id — undefined for PERSONAL
  contextLabel?: string; // sector / institute name
  status: string;
}

const TYPE_META: Record<
  UnifiedKycType,
  { label: string; icon: React.ElementType; badgeClass: string }
> = {
  PERSONAL: {
    label: 'Personal KYC',
    icon: UserCheck,
    badgeClass: 'bg-primary/10 text-primary border-primary/20',
  },
  SECTOR: {
    label: 'Sector Agreement',
    icon: Layers,
    badgeClass: 'bg-indigo-500/10 text-indigo-500 border-indigo-500/20',
  },
  INSTITUTE: {
    label: 'Institute Agreement',
    icon: Home,
    badgeClass: 'bg-sky-500/10 text-sky-500 border-sky-500/20',
  },
};

function StatusBadge({ status }: { status: string }) {
  if (status === 'APPROVED') {
    return (
      <span className="inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-bold rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20">
        <CheckCircle2 className="h-3 w-3" />
        <span>Approved</span>
      </span>
    );
  }
  if (status === 'UNDER_REVIEW' || status === 'UNDER_APPROVAL') {
    return (
      <span className="inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-bold rounded-full bg-amber-500/10 text-amber-500 border border-amber-500/20">
        <Clock className="h-3 w-3 animate-spin" />
        <span>{status === 'UNDER_APPROVAL' ? 'Awaiting Review' : 'Under Review'}</span>
      </span>
    );
  }
  return (
    <span className="inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-bold rounded-full bg-destructive/10 text-destructive border border-destructive/20">
      <XCircle className="h-3 w-3" />
      <span>{status.replace(/_/g, ' ')}</span>
    </span>
  );
}

export default function PendingApprovalsManagementPage() {
  const [search, setSearch] = useState('');
  const [roleFilter, setRoleFilter] = useState('');
  const [kycTypeFilter, setKycTypeFilter] = useState<UnifiedKycType | ''>('');
  const [page, setPage] = useState(1);
  const [selectedUser, setSelectedUser] = useState<UserPendingApprovalRecord | null>(null);

  // Per-row inline remarks for quick agreement approvals (sector / institute)
  const [quickRemarks, setQuickRemarks] = useState<{ [rowKey: string]: string }>({});

  const { data, isLoading, refetch } = usePendingApprovals({
    page,
    limit: 10,
    search,
    role: roleFilter,
  });

  const reviewSectorKycMutation = useReviewSectorKyc();
  const reviewInstituteKycMutation = useReviewInstituteKyc();

  // Flatten users -> one row per pending KYC item (personal / sector / institute)
  const unifiedRows: UnifiedKycRow[] = useMemo(() => {
    const rows: UnifiedKycRow[] = [];

    (data?.items || []).forEach((user) => {
      // Personal KYC — covers career advisors, DSOs, institute admins doing
      // their own identity verification. Only surface if not already approved.
      if (user.kycRecord && user.kycRecord.status !== 'APPROVED') {
        rows.push({
          key: `personal-${user.id}`,
          type: 'PERSONAL',
          user,
          status: user.kycRecord.status,
        });
      }

      // Sector agreement requests (District-Sector Owners)
      ((user as any).sectorKycRequests || []).forEach((req: any) => {
        if (req.status === 'UNDER_APPROVAL') {
          rows.push({
            key: `sector-${req.id}`,
            type: 'SECTOR',
            user,
            requestId: req.id,
            contextLabel: req.sector?.name,
            status: req.status,
          });
        }
      });

      // Institute agreement requests (Institute Admins)
      ((user as any).instituteKycRequests || []).forEach((req: any) => {
        if (req.status === 'UNDER_APPROVAL') {
          rows.push({
            key: `institute-${req.id}`,
            type: 'INSTITUTE',
            user,
            requestId: req.id,
            contextLabel: req.institute?.name,
            status: req.status,
          });
        }
      });
    });

    return kycTypeFilter ? rows.filter((r) => r.type === kycTypeFilter) : rows;
  }, [data, kycTypeFilter]);

  const handleQuickReview = async (row: UnifiedKycRow, decision: 'APPROVED' | 'REJECTED') => {
    if (!row.requestId) return;
    const remarks = quickRemarks[row.key] || '';

    if (row.type === 'SECTOR') {
      await reviewSectorKycMutation.mutateAsync({
        requestId: row.requestId,
        status: decision,
        remarks,
        rejectionReason: decision === 'REJECTED' ? remarks || 'Sector agreement verification failed.' : undefined,
      });
    } else if (row.type === 'INSTITUTE') {
      await reviewInstituteKycMutation.mutateAsync({
        requestId: row.requestId,
        status: decision,
        remarks,
        rejectionReason: decision === 'REJECTED' ? remarks || 'Institute agreement verification failed.' : undefined,
      });
    }
    refetch();
  };

  const columns: Column<UnifiedKycRow>[] = [
    {
      header: 'Type',
      className: 'w-40',
      cell: (row) => {
        const meta = TYPE_META[row.type];
        const Icon = meta.icon;
        return (
          <span
            className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md border text-[10px] font-bold tracking-wider uppercase ${meta.badgeClass}`}
          >
            <Icon className="h-3 w-3" />
            <span>{meta.label}</span>
          </span>
        );
      },
    },
    {
      header: 'Applicant',
      className: 'min-w-[220px]',
      cell: (row) => {
        const { user } = row;
        return (
          <div className="flex items-center gap-2.5 text-left">
            <div className="h-7 w-7 rounded-lg bg-primary/10 border border-primary/20 flex items-center justify-center text-xs font-bold text-primary shrink-0">
              {user.firstName ? user.firstName[0] : 'U'}
              {user.lastName ? user.lastName[0] : ''}
            </div>
            <div className="flex flex-col">
              <span className="text-foreground font-semibold tracking-tight text-xs">
                {user.firstName} {user.lastName}
              </span>
              <span className="text-[10px] text-muted-foreground/70 font-medium">{user.email}</span>
            </div>
          </div>
        );
      },
    },
    {
      header: 'Role Tier',
      className: 'w-40',
      cell: (row) => (
        <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md bg-muted/40 border border-border/40 text-[10px] font-bold tracking-wider text-foreground uppercase">
          <Shield className="h-3 w-3 text-primary" />
          <span>{row.user.role ? row.user.role.replace(/_/g, ' ') : 'N/A'}</span>
        </span>
      ),
    },
    {
      header: 'Context',
      className: 'w-48',
      cell: (row) => (
        <span className="text-xs font-medium text-foreground">{row.contextLabel || '—'}</span>
      ),
    },
    {
      header: 'Status',
      className: 'w-36',
      cell: (row) => <StatusBadge status={row.status} />,
    },
    {
      header: 'Actions',
      className: 'w-64 text-right',
      cell: (row) => {
        if (row.type === 'PERSONAL') {
          return (
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setSelectedUser(row.user)}
              className="h-7 px-2 text-[10px] font-bold gap-1 text-primary hover:text-primary hover:bg-primary/10 cursor-pointer"
            >
              <span>Manage</span>
              <ChevronRight className="h-3 w-3" />
            </Button>
          );
        }

        // Sector / Institute agreement — quick inline approve/reject
        const isPending = reviewSectorKycMutation.isPending || reviewInstituteKycMutation.isPending;
        return (
          <div className="flex items-center justify-end gap-1.5">
            <input
              type="text"
              placeholder="Remarks..."
              value={quickRemarks[row.key] || ''}
              onChange={(e) => setQuickRemarks({ ...quickRemarks, [row.key]: e.target.value })}
              className="w-28 text-[10px] px-2 py-1 border border-border/40 rounded bg-background focus:outline-none focus:border-primary"
            />
            <Button
              variant="outline"
              size="sm"
              disabled={isPending}
              onClick={() => handleQuickReview(row, 'REJECTED')}
              className="h-7 px-2 text-[10px] font-bold border-destructive/30 text-destructive hover:bg-destructive/10 cursor-pointer"
            >
              Reject
            </Button>
            <Button
              size="sm"
              disabled={isPending}
              onClick={() => handleQuickReview(row, 'APPROVED')}
              className="h-7 px-2 text-[10px] font-bold bg-emerald-600 hover:bg-emerald-700 text-white cursor-pointer"
            >
              Approve
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setSelectedUser(row.user)}
              className="h-7 px-1.5 text-[10px] text-muted-foreground hover:text-foreground cursor-pointer"
              title="View full applicant profile"
            >
              <ChevronRight className="h-3 w-3" />
            </Button>
          </div>
        );
      },
    },
  ];

  if (isLoading) return <TableSkeleton />;

  return (
    <>
      <div className="space-y-4 max-w-7xl mx-auto animate-in fade-in duration-300 select-none">
        <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">
              Pending Onboarding & Approvals
            </h1>
            <p className="text-[11px] font-medium text-muted-foreground/70">
              Review personal KYC, sector agreements, and institute agreements — all in one place.
            </p>
          </div>
        </div>

        <div className="flex flex-wrap items-center justify-between gap-3">
          <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 by name, email, or system code..."
              value={search}
              onChange={(e) => {
                setSearch(e.target.value);
                setPage(1);
              }}
              className="w-full text-xs font-medium pl-8 pr-3 py-2 border border-border/40 bg-surface rounded-lg text-foreground focus:outline-none focus:border-primary"
            />
          </div>

          <div className="flex items-center gap-2">
            <Filter className="h-3.5 w-3.5 text-muted-foreground/60" />

            <select
              value={kycTypeFilter}
              onChange={(e) => setKycTypeFilter(e.target.value as UnifiedKycType | '')}
              className="text-xs font-medium px-3 py-2 border border-border/40 bg-surface rounded-lg text-foreground focus:outline-none focus:border-primary cursor-pointer"
            >
              <option value="">All KYC Types</option>
              <option value="PERSONAL">Personal KYC</option>
              <option value="SECTOR">Sector Agreement</option>
              <option value="INSTITUTE">Institute Agreement</option>
            </select>

            <select
              value={roleFilter}
              onChange={(e) => {
                setRoleFilter(e.target.value);
                setPage(1);
              }}
              className="text-xs font-medium px-3 py-2 border border-border/40 bg-surface rounded-lg text-foreground focus:outline-none focus:border-primary cursor-pointer"
            >
              <option value="">All Role Tiers</option>
              <option value="STATE_OWNER">State Owner</option>
              <option value="DISTRICT_OWNER">District Owner</option>
              <option value="DISTRICT_SECTOR_OWNER">District-Sector Owner</option>
              <option value="INSTITUTE_ADMIN">Institute Admin</option>
              <option value="CAREER_ADVISOR">Career Advisor</option>
            </select>
          </div>
        </div>

        <DataTable
          data={unifiedRows}
          columns={columns}
          emptyMessage="No pending KYC items found matching current filters."
          pagination={
            data
              ? {
                  page: data.page,
                  pages: data.pages,
                  total: data.total,
                  onPageChange: setPage,
                }
              : undefined
          }
        />
      </div>

      {selectedUser && (
        <PendingApprovalManagementDrawer
          user={selectedUser}
          onClose={() => setSelectedUser(null)}
          onRefresh={() => {
            refetch();
          }}
        />
      )}
    </>
  );
}