'use client';

import React, { useCallback, useMemo, useState } from 'react';
import { Plus, FileText, Ticket, ArrowRightLeft } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { DataTable, Column } from '@/components/ui/data-table';
import { TableSkeleton } from '@/components/ui/tableSkeleton';
import { usePurchaseOrders } from '@/services/purchase-orders/queries';
import { PurchaseOrderRecord, PurchaseOrderType, PurchaseOrderScope } from '@/services/purchase-orders/types';
import CreatePurchaseOrderModal from './_components/CreatePurchaseOrderModal';
import PurchaseOrderDrawer from './_components/PurchaseOrderDrawer';
import { useProfile } from '@/services/users/queries';
import { useCoupons, useSelfAllocateCoupons } from '@/services/coupons/queries';
import { CouponRecord, DsoWorkspaceMode } from '@/services/coupons/types';
import { useAppSelector } from '@/store/hooks';
import { SYSTEM_ADMIN_ROLES } from '@/services/users/types';

const STATUS_STYLES: Record<string, string> = {
  PENDING: 'bg-amber-500/10 text-amber-500 border-amber-500/20',
  ACCOUNTS_APPROVED: 'bg-sky-500/10 text-sky-500 border-sky-500/20',
  ACCOUNTS_REJECTED: 'bg-destructive/10 text-destructive border-destructive/20',
  COUPONS_ASSIGNED: 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20',
  REJECTED: 'bg-destructive/10 text-destructive border-destructive/20',
  CANCELLED: 'bg-muted/40 text-muted-foreground border-border/40',
};

const COUPON_STATUS_STYLES: Record<string, string> = {
  AVAILABLE: 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20',
  ASSIGNED_TO_DSO: 'bg-sky-500/10 text-sky-500 border-sky-500/20',
  ASSIGNED_TO_INSTITUTE: 'bg-indigo-500/10 text-indigo-500 border-indigo-500/20',
  ASSIGNED_TO_CAREER_ADVISOR: 'bg-purple-500/10 text-purple-500 border-purple-500/20',
  REDEEMED: 'bg-muted/40 text-muted-foreground border-border/40',
  REVOKED: 'bg-destructive/10 text-destructive border-destructive/20',
};

function resolveRaisedTo(po: PurchaseOrderRecord): string {
  if (po.type === 'DSO_TO_ADMIN' || po.type === 'INSTITUTE_TO_ADMIN' || po.type === 'CAREER_ADVISOR_TO_ADMIN') {
    return 'Central Admin System';
  }
  if (po.type === 'INSTITUTE_TO_DSO') {
    const dsoUser = po.districtSectorOwner?.user;
    if (dsoUser) return `${dsoUser.firstName} ${dsoUser.lastName} (DSO)`;
    return 'District Sector Owner';
  }
  if (po.type === 'CAREER_ADVISOR_TO_INSTITUTE') {
    const instName = po.institute?.name || po.careerAdvisor?.institute?.name;
    return instName ? `${instName} (Institute)` : 'Institute Admin';
  }
  return '—';
}

/**
 * Capability resolution, persona-aware for DISTRICT_SECTOR_OWNER.
 *
 * IMPORTANT: DSO and RESELLER personas both raise a DSO_TO_ADMIN PO — there
 * is no 'RESELLER_TO_ADMIN' type on the backend. The persona is carried by
 * `workspaceMode` in the create payload, not by `type`.
 */
function resolveRoleCapabilities(role?: string, workspaceMode?: DsoWorkspaceMode) {
  if (role === 'DISTRICT_SECTOR_OWNER') {
    if (workspaceMode === 'INSTITUTE') {
      return {
        canRaise: { type: 'INSTITUTE_TO_ADMIN' as PurchaseOrderType, label: 'Admin (Central Inventory) — Kit Eligible' },
        canReview: false,
        canAssign: true,
        canAccess: true,
        isTargetRecipient: true,
      };
    }

    return {
      canRaise: {
        type: 'DSO_TO_ADMIN' as PurchaseOrderType,
        label:
          workspaceMode === 'RESELLER'
            ? 'Central Admin System (Reseller Stock)'
            : 'Central Admin System (Territory Stock)',
      },
      canReview: false,
      canAssign: true,
      canAccess: true,
      isTargetRecipient: true,
    };
  }

  const canReview = role === 'ACCOUNTS' || role === 'ADMIN' || role === 'SUPER_ADMIN';
  const canAssign =
    role === 'ADMIN' || role === 'SUPER_ADMIN' || role === 'INVENTORY_MANAGER' || role === 'INSTITUTE_ADMIN';

  const canAccess =
    role === 'ADMIN' ||
    role === 'SUPER_ADMIN' ||
    role === 'INVENTORY_MANAGER' ||
    role === 'INSTITUTE_ADMIN' ||
    role === 'CAREER_ADVISOR';

  const isTargetRecipient =
    role === 'INSTITUTE_ADMIN' || role === 'ADMIN' || role === 'SUPER_ADMIN';

  const canRaise =
    role === 'INSTITUTE_ADMIN'
      ? { type: 'INSTITUTE_TO_ADMIN' as PurchaseOrderType, label: 'Central Admin System' }
      : role === 'CAREER_ADVISOR'
      ? { type: 'CAREER_ADVISOR_TO_INSTITUTE' as PurchaseOrderType, label: 'Your Institute' }
      : null;

  return { canRaise, canReview, canAssign, canAccess, isTargetRecipient };
}

export default function PurchaseOrdersPage() {
  const { data: profile } = useProfile();
  const currentUser = (profile as any)?.data || profile;
  const userRole = currentUser?.role;
  const isDso = userRole === 'DISTRICT_SECTOR_OWNER';

  console.log('currentUser', currentUser);

  const isSystemRole = SYSTEM_ADMIN_ROLES.includes(userRole || '');

  const activeDsoMode = useAppSelector((s) => s.ui.dsoWorkspaceMode) as DsoWorkspaceMode | undefined;
  const { canRaise, canReview, canAssign, canAccess, isTargetRecipient } = resolveRoleCapabilities(
    userRole,
    isDso ? activeDsoMode : undefined
  );

  const [scope, setScope] = useState<PurchaseOrderScope | 'inventory'>('mine');
  const [poPage, setPoPage] = useState(1);
  const [couponPage, setCouponPage] = useState(1);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [selectedPo, setSelectedPo] = useState<PurchaseOrderRecord | null>(null);

  // Persona-scoped PO list — a DSO's "My Raised Orders" only ever shows POs
  // raised under the currently active persona (Territory / Reseller / Institute).
  const poQuery = usePurchaseOrders(
    poPage,
    scope === 'inventory' ? 'mine' : scope,
    '',
    '',
    isDso ? activeDsoMode : undefined
  );

  console.log('poQuery', poQuery);

  const [selectedCouponIds, setSelectedCouponIds] = useState<string[]>([]);
  const selfAllocateMutation = useSelfAllocateCoupons();

  // Persona-scoped coupon inventory — Territory / Reseller / Institute pools
  // never bleed into one another here.
  const couponQuery = useCoupons(
    couponPage,
    '',
    '',
    'mine',
    '',
    undefined,
    isDso ? activeDsoMode : undefined
  );

  const handleSelectCoupon = useCallback((id: string) => {
    setSelectedCouponIds((prev) => (prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]));
  }, []);

  const handleSelectAllCoupons = useCallback(() => {
    const currentItems = couponQuery.data?.items || [];
    if (selectedCouponIds.length === currentItems.length) {
      setSelectedCouponIds([]);
    } else {
      setSelectedCouponIds(currentItems.map((c) => c.id));
    }
  }, [couponQuery.data?.items, selectedCouponIds.length]);

  const handleTransferToSelf = async () => {
    if (selectedCouponIds.length === 0) return;
    await selfAllocateMutation.mutateAsync(selectedCouponIds);
    setSelectedCouponIds([]);
  };

  const tabs = useMemo(() => {
    const list: { key: PurchaseOrderScope | 'inventory'; label: string }[] = [];

    // Only add "My Raised Orders" for field/tenant roles, hide for administrative system roles
    if (!isSystemRole) {
      list.push({ key: 'mine', label: 'My Raised Orders' });
    }

    if (isTargetRecipient) list.push({ key: 'assigned_to_me', label: 'Orders Raised To Me' });
    if (canReview) list.push({ key: 'review', label: 'Accounts Review Queue' });
    if (canAssign) list.push({ key: 'assign', label: 'Coupon Assignment Queue' });
    list.push({ key: 'inventory', label: 'My Coupon Inventory' });
    return list;
  }, [isSystemRole, canReview, canAssign, isTargetRecipient]);

  const poColumns: Column<PurchaseOrderRecord>[] = [
    {
      header: 'PO Number',
      className: 'w-36 font-mono font-bold text-primary text-xs',
      cell: (po) => (
        <div className="flex flex-col">
          <span className="font-mono text-xs font-bold text-primary">{po.poNumber}</span>
          <span className="text-[10px] text-muted-foreground/60 font-semibold uppercase tracking-tight">
            {po.type ? po.type.replace(/_/g, ' → ') : '—'}
            {po.dsoWorkspaceMode ? ` · ${po.dsoWorkspaceMode}` : ''}
          </span>
        </div>
      ),
    },
    {
      header: 'Raised By (Requester)',
      className: 'min-w-[190px]',
      cell: (po) => {
        const name = po.createdBy ? `${po.createdBy.firstName || ''} ${po.createdBy.lastName || ''}`.trim() : 'Unknown Requester';
        const subText = po.institute?.name
          ? `${po.institute.name} (${po.institute.code})`
          : po.createdBy?.role
          ? po.createdBy.role.replace(/_/g, ' ')
          : 'User';
        return (
          <div className="flex flex-col max-w-[210px] truncate">
            <span className="text-xs font-semibold text-foreground truncate">{name}</span>
            <span className="text-[10px] text-muted-foreground/70 font-mono truncate">{subText}</span>
          </div>
        );
      },
    },
    {
      header: 'Raised To (Target)',
      className: 'min-w-[190px]',
      cell: (po) => {
        const target = resolveRaisedTo(po);
        const sectorName = po.districtSectorOwner?.districtSector?.sector?.name;
        const districtName = po.districtSectorOwner?.districtSector?.district?.name;
        return (
          <div className="flex flex-col max-w-[210px] truncate">
            <span className="text-xs font-bold text-foreground truncate">{target}</span>
            {sectorName && (
              <span className="text-[10px] text-muted-foreground/70 font-mono truncate">
                Sector: {sectorName} {districtName ? `(${districtName})` : ''}
              </span>
            )}
          </div>
        );
      },
    },
    {
      header: 'Quantity',
      className: 'w-24 text-center',
      cell: (po) => (
        <div className="flex justify-center">
          <span className="text-xs font-bold text-foreground bg-muted/30 px-2.5 py-1 rounded-md border border-border/30 font-mono">
            {po.quantityAsked ?? 0}
          </span>
        </div>
      ),
    },
    {
      header: 'Status',
      className: 'w-36',
      cell: (po) => (
        <span
          className={`inline-flex items-center px-2.5 py-0.5 text-[10px] font-bold rounded-full border uppercase ${
            STATUS_STYLES[po.status] || 'bg-muted/40 text-muted-foreground border-border/40'
          }`}
        >
          {po.status ? po.status.replace(/_/g, ' ') : 'UNKNOWN'}
        </span>
      ),
    },
    {
      header: 'Raised On',
      className: 'w-28',
      cell: (po) => (
        <span className="text-[11px] text-muted-foreground/70 font-mono whitespace-nowrap">
          {po.createdAt ? new Date(po.createdAt).toLocaleDateString() : '—'}
        </span>
      ),
    },
    {
      header: 'Actions',
      className: 'w-24 text-right',
      cell: (po) => (
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setSelectedPo(po)}
          className="h-7 px-2 text-[10px] font-bold cursor-pointer hover:bg-primary/10 hover:text-primary shrink-0"
        >
          View Details
        </Button>
      ),
    },
  ];

  const showBulkSelect = isDso && activeDsoMode === 'DSO'; // self-allocate only makes sense moving Territory → Reseller

  const couponColumns = useMemo<Column<CouponRecord>[]>(() => {
    const cols: Column<CouponRecord>[] = [];

    if (showBulkSelect) {
      cols.push({
        header: (
          <input
            type="checkbox"
            checked={
              (couponQuery.data?.items?.length ?? 0) > 0 &&
              selectedCouponIds.length === (couponQuery.data?.items?.length ?? 0)
            }
            onChange={handleSelectAllCoupons}
            className="h-3.5 w-3.5 rounded border-border/60 text-primary focus:ring-primary cursor-pointer"
          />
        ) as unknown as string,
        className: 'w-10 text-center',
        cell: (c: CouponRecord) => (
          <input
            type="checkbox"
            checked={selectedCouponIds.includes(c.id)}
            onChange={() => handleSelectCoupon(c.id)}
            className="h-3.5 w-3.5 rounded border-border/60 text-primary focus:ring-primary cursor-pointer"
          />
        ),
      });
    }

    cols.push(
      {
        header: 'Public Code',
        className: 'w-44 font-mono font-bold text-primary text-xs',
        cell: (c) => <span className="font-mono text-xs font-bold text-primary">{c.code}</span>,
      },
      {
        header: 'Official Code',
        className: 'min-w-[200px]',
        cell: (c) => {
          // Explicit UI override: Force mask if DSO is in Territory mode and coupon is not self-store
          const shouldMaskInUi =
            isDso &&
            activeDsoMode === 'DSO' &&
            !c.isSelfStore;

          const isCodeHidden = c.isHidden || shouldMaskInUi;

          return (
            <span className="font-mono text-xs font-semibold text-foreground">
              {isCodeHidden ? '••••-••••-••••' : c.officialCode}
            </span>
          );
        },
      },
      {
        header: 'Status',
        className: 'w-48',
        cell: (c) => (
          <span className={`inline-flex px-2.5 py-0.5 text-[10px] font-bold rounded-full border uppercase ${COUPON_STATUS_STYLES[c.status] || ''}`}>
            {c.status ? c.status.replace(/_/g, ' ') : 'UNKNOWN'}
          </span>
        ),
      },
      {
        header: 'Pool',
        className: 'min-w-[160px]',
        cell: (c) =>
          isDso ? (
            <span className="text-xs font-semibold text-muted-foreground/80">
              {activeDsoMode === 'RESELLER' ? 'Reseller Store' : activeDsoMode === 'INSTITUTE' ? 'Institute Inventory' : 'Territory Pool'}
            </span>
          ) : (
            <span className="text-xs text-muted-foreground/60">—</span>
          ),
      },
      {
        header: 'Created On',
        className: 'w-32',
        cell: (c) => <span className="text-[11px] font-mono">{new Date(c.createdAt).toLocaleDateString()}</span>,
      }
    );

    return cols;
  }, [showBulkSelect, selectedCouponIds, couponQuery.data?.items, handleSelectAllCoupons, handleSelectCoupon, isDso, activeDsoMode]);

  if (poQuery.isLoading && scope !== 'inventory') 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 flex items-center gap-2">
              <FileText className="h-4 w-4 text-primary" /> Purchase Orders & Inventory
              {isDso && (
                <span className="text-[10px] font-bold px-2 py-0.5 rounded-full bg-primary/10 text-primary border border-primary/20 normal-case tracking-normal">
                  {activeDsoMode === 'RESELLER' ? 'Reseller Persona' : activeDsoMode === 'INSTITUTE' ? 'Institute Persona' : 'Territory Persona'}
                </span>
              )}
            </h1>
            <p className="text-[11px] font-medium text-muted-foreground/70">
              Raise coupon requests, review payments, and track active coupon holdings.
            </p>
          </div>

          {canRaise && (
            <Button
              onClick={() => setShowCreateModal(true)}
              className="h-8 rounded-md px-3 text-[11px] font-bold tracking-wider uppercase shadow-sm gap-1.5 bg-foreground text-background hover:bg-foreground/90 cursor-pointer"
            >
              <Plus className="h-3.5 w-3.5 stroke-[2.5]" /> Raise Purchase Order
            </Button>
          )}
        </div>

        <div className="flex items-center justify-between border-b border-border/10">
          <div className="flex items-center gap-1">
            {tabs.map((tab) => (
              <button
                key={tab.key}
                onClick={() => {
                  setScope(tab.key);
                  setPoPage(1);
                  setCouponPage(1);
                  setSelectedCouponIds([]);
                }}
                className={`px-3 py-2 text-[11px] font-bold uppercase tracking-wider border-b-2 transition-colors cursor-pointer ${
                  scope === tab.key ? 'border-primary text-primary' : 'border-transparent text-muted-foreground/60 hover:text-foreground'
                }`}
              >
                {tab.label}
              </button>
            ))}
          </div>

          {scope === 'inventory' && couponQuery.data && (
            <div className="flex items-center gap-2 text-xs font-bold text-muted-foreground pr-1 pb-1 font-mono">
              <Ticket className="h-4 w-4 text-primary" />
              <span>Total Coupons Held: {couponQuery.data.total}</span>
            </div>
          )}
        </div>

        {scope === 'inventory' && showBulkSelect && selectedCouponIds.length > 0 && (
          <div className="flex items-center justify-between p-2.5 bg-primary/10 border border-primary/20 rounded-lg animate-in fade-in duration-150">
            <span className="text-xs font-bold text-primary flex items-center gap-2">
              <Ticket className="h-4 w-4" />
              {selectedCouponIds.length} coupon(s) selected
            </span>
            <Button
              size="sm"
              onClick={handleTransferToSelf}
              disabled={selfAllocateMutation.isPending}
              className="h-7 text-xs font-bold bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm gap-1.5 cursor-pointer"
            >
              <ArrowRightLeft className="h-3.5 w-3.5" />
              {selfAllocateMutation.isPending ? 'Transferring…' : 'Transfer to Self Store'}
            </Button>
          </div>
        )}

        {scope === 'inventory' ? (
          couponQuery.isLoading ? (
            <TableSkeleton />
          ) : (
            <DataTable
              data={couponQuery.data?.items || []}
              columns={couponColumns}
              emptyMessage="No coupons found in your personal inventory."
              pagination={
                couponQuery.data
                  ? { page: couponQuery.data.page, pages: couponQuery.data.pages, total: couponQuery.data.total, onPageChange: setCouponPage }
                  : undefined
              }
            />
          )
        ) : (
          <DataTable
            data={poQuery.data?.items || []}
            columns={poColumns}
            emptyMessage="No purchase orders found in this queue."
            pagination={
              poQuery.data
                ? { page: poQuery.data.page, pages: poQuery.data.pages, total: poQuery.data.total, onPageChange: setPoPage }
                : undefined
            }
          />
        )}
      </div>

      {showCreateModal && canRaise && (
        <CreatePurchaseOrderModal
          poType={canRaise.type}
          poTypeLabel={canRaise.label}
          workspaceMode={isDso ? activeDsoMode : undefined}
          onClose={() => setShowCreateModal(false)}
        />
      )}

      {selectedPo && (
        <PurchaseOrderDrawer
          po={selectedPo}
          currentUserId={currentUser?.id}
          scope={scope === 'inventory' ? 'mine' : scope}
          onClose={() => setSelectedPo(null)}
          onRefresh={() => poQuery.refetch()}
        />
      )}
    </>
  );
}