'use client';

import React, { useState } from 'react';
import {
  Layers, Home, UserCheck, Users, TrendingUp, BarChart3, Download,
  AlertTriangle, CheckCircle, Clock, XCircle, FileCheck, Upload
} from 'lucide-react';
import toast from 'react-hot-toast';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { useDashboardMetrics } from '@/services/superAdmin/queries';
import { dashboardApi } from '@/services/superAdmin/api';
import { useMySectorKycRequests } from '@/services/sectorKyc/queries';
import { useMyKycRecord } from '@/services/kyc/queries';
import { SectorKycRequestItem } from '@/services/sectorKyc/api';
import { DsoWorkspaceMode } from '@/services/coupons/types';

import {
  EnrollmentTrendsChart,
  DistrictPerformanceChart,
  SectorGrowthChart,
  ConversionFunnelChart
} from '@/components/dashboard/charts';
import SubmitAgreementModal from './SubmitAgreementModal';
import UploadMyKycModal from '@/components/ui/UploadMyKycModal';
import DSOSelfCouponView from './DSOSelfCouponView';
import DsoInstituteCouponView from './DsoInstituteCouponView';

interface Props {
  userContext: any;
  workspaceMode?: DsoWorkspaceMode; // 'DSO' | 'RESELLER' | 'INSTITUTE'
}

export default function DistrictSectorOwnerView({ userContext, workspaceMode = 'DSO' }: Props) {
  // Dashboard metrics query already forwards workspaceMode server-side
  // (see useDashboardMetrics hook — pass workspaceMode through if not
  // already wired). Territory metrics serve both DSO and RESELLER personas;
  // Institute persona gets its own scoped metrics from the backend.
  const { data: metrics, isError, isLoading } = useDashboardMetrics(workspaceMode);
  const { data: sectorKycRequests, isLoading: isSectorKycLoading } = useMySectorKycRequests();
  const { data: personalKycRecord, isLoading: isPersonalKycLoading } = useMyKycRecord();

  const [activeModalRequest, setActiveModalRequest] = useState<SectorKycRequestItem | null>(null);
  const [isPersonalKycModalOpen, setIsPersonalKycModalOpen] = useState(false);

  const isPersonalKycApproved = personalKycRecord?.status === 'APPROVED';
  const pendingSectorKycs = sectorKycRequests?.filter(
    (r) => r.status === 'AGREEMENT_PENDING' || r.status === 'REJECTED'
  );

  const chartData = {
    institutePerformance: metrics?.charts?.institutePerformance?.length ? metrics.charts.institutePerformance : [],
    trends: metrics?.charts?.trends?.length ? metrics.charts.trends : [],
    funnel: metrics?.charts?.funnel?.length
      ? metrics.charts.funnel.map((item: any, idx: number) => ({
          ...item,
          fill: idx === 0 ? 'var(--primary)' : `rgba(var(--primary-rgb), ${1 - idx * 0.22})`
        }))
      : []
  };

  const handleExport = async () => {
    try {
      toast.loading("Compiling framework matrix analytics...", { id: "matrix-export" });
      await dashboardApi.exportPerformanceReport();
      toast.success("Cross-District Matrix Logs Dispatched.", { id: "matrix-export" });
    } catch (error) {
      console.error("Export failed:", error);
      toast.error("Export stream pipeline execution interrupted.", { id: "matrix-export" });
    }
  };

  if (isLoading || isSectorKycLoading || isPersonalKycLoading) {
    return (
      <div className="p-8 space-y-4 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 animate-pulse max-w-7xl mx-auto">
        {[...Array(8)].map((_, i) => (
          <div key={i} className="h-24 bg-muted/20 rounded-xl border border-border/10" />
        ))}
      </div>
    );
  }

  // 🌟 Direct Reseller Mode Perspective
  if (workspaceMode === 'RESELLER') {
    return (
      <div className="space-y-6 max-w-7xl mx-auto animate-in fade-in duration-300">
        <div className="border-b border-border/40 pb-4">
          <h1 className="text-sm font-black tracking-widest text-foreground uppercase">
            DIRECT RESELLER & SELF-COUPON CONTROL HUB
          </h1>
          <p className="text-[11px] font-medium text-muted-foreground/70">
            Manage your unhidden official coupon inventory and execute direct student enrollments.
          </p>
        </div>
        <DSOSelfCouponView />
      </div>
    );
  }

  // 🎓 Direct Institute Mode Perspective
  if (workspaceMode === 'INSTITUTE') {
    if (metrics?.notGranted) {
      return (
        <div className="p-8 text-center text-xs font-semibold text-muted-foreground border border-dashed border-border/30 rounded-xl max-w-7xl mx-auto">
          You have not been granted an Institute persona yet. Contact your Administrator to enable Institute mode.
        </div>
      );
    }
    return (
      <div className="space-y-6 max-w-7xl mx-auto animate-in fade-in duration-300">
        <div className="border-b border-border/40 pb-4">
          <h1 className="text-sm font-black tracking-widest text-foreground uppercase">
            DIRECT INSTITUTE OPERATIONS TERMINAL
          </h1>
          <p className="text-[11px] font-medium text-muted-foreground/70">
            Manage career advisors, Kit purchase orders, and your Institute-scoped coupon inventory.
          </p>
        </div>
        <DsoInstituteCouponView />
      </div>
    );
  }

  if (isError || !metrics) {
    return (
      <div className="p-8 text-center text-xs font-semibold tracking-wider text-destructive border border-dashed border-destructive/20 rounded-xl bg-destructive/5 max-w-7xl mx-auto">
        Could not fetch active matrix domain records. Please check token configurations.
      </div>
    );
  }

  // Standard Territory Matrix Perspective (also serves as the base analytics
  // view for the DSO persona — Reseller shares these same underlying
  // Territory numbers since it's only a coupon-pool split, not a separate
  // organizational scope).
  return (
    <div className="space-y-8 max-w-7xl mx-auto animate-in fade-in slide-in-from-bottom-2 duration-500 select-none">

      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 border-b border-border/40 pb-6">
        <div className="space-y-0.5">
          <h1 className="text-sm font-black tracking-widest text-foreground uppercase">CROSS-SECTOR MANAGEMENT TERMINAL</h1>
          <p className="text-[11px] font-medium text-muted-foreground/70">
            Welcome back, {userContext?.firstName} {userContext?.lastName} • Scoped Multi-District Matrix Jurisdiction.
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Button
            onClick={handleExport}
            variant="outline"
            className="h-8 rounded-md px-3 text-[11px] font-bold tracking-wider uppercase shadow-sm gap-1.5 border-border/80 hover:bg-muted/60 text-foreground transition-all"
          >
            <Download className="h-3 w-3" />
            <span>Export Matrix Dossier</span>
          </Button>
        </div>
      </div>

      {!isPersonalKycApproved && (
        <div className="border border-amber-500/30 bg-amber-500/10 p-4 rounded-xl flex items-start justify-between gap-4">
          <div className="flex items-start gap-3">
            <AlertTriangle className="h-5 w-5 text-amber-500 shrink-0 mt-0.5" />
            <div className="space-y-1">
              <h3 className="text-xs font-bold uppercase tracking-wider text-amber-500">
                Action Required: Personal KYC Documents Pending ({personalKycRecord?.status || 'NOT_SUBMITTED'})
              </h3>
              <p className="text-[11px] font-medium text-amber-200/80">
                You must upload your government ID proof documents to activate your account.
              </p>
            </div>
          </div>
          {personalKycRecord?.status !== 'UNDER_REVIEW' && (
            <Button
              size="sm"
              onClick={() => setIsPersonalKycModalOpen(true)}
              className="h-8 text-xs font-bold bg-amber-500 text-black hover:bg-amber-600 shrink-0"
            >
              <Upload className="h-3.5 w-3.5 mr-1" /> Upload Personal KYC
            </Button>
          )}
        </div>
      )}

      {pendingSectorKycs && pendingSectorKycs.length > 0 && (
        <div className="border border-sky-500/30 bg-sky-500/10 p-4 rounded-xl flex items-start justify-between gap-4">
          <div className="flex items-start gap-3">
            <FileCheck className="h-5 w-5 text-sky-500 shrink-0 mt-0.5" />
            <div className="space-y-1">
              <h3 className="text-xs font-bold uppercase tracking-wider text-sky-500">
                Action Required: {pendingSectorKycs.length} Pending Sector Agreement(s)
              </h3>
              <p className="text-[11px] font-medium text-sky-200/80">
                Upload signed agreement documents for your assigned sector nodes.
              </p>
            </div>
          </div>
        </div>
      )}

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {[
          { title: "Assigned Sectors", value: metrics.widgets.totalAssignedSectors ?? 0, sub: "Mapped Functional Sectors", icon: Layers },
          { title: "Cross-Institutes", value: metrics.widgets.totalInstitutes ?? 0, sub: "Active Sub-Campus Nodes", icon: Home },
          { title: "Fleet Advisors", value: metrics.widgets.activeAdvisors ?? 0, sub: "Active Scoped Personnel", icon: UserCheck, highlight: true },
          { title: "Total Matrix Enrolled", value: metrics.widgets.totalStudents ?? 0, sub: "Aggregated Student Pipeline", icon: Users },
          { title: "Today's Scoped Influx", value: metrics.widgets.todayRegistrations || 0, sub: "Live Registration Vector", icon: TrendingUp, success: true },
          { title: "Personal KYC Status", value: personalKycRecord?.status || 'PENDING', sub: "Universal Compliance", icon: BarChart3, danger: !isPersonalKycApproved },
        ].map((w, idx) => (
          <Card key={idx} className={`shadow-none rounded-xl border border-border/40 bg-surface backdrop-blur-md transition-all hover:border-border/80 ${w.highlight ? 'border-l-primary border-l-2' : ''}`}>
            <CardHeader className="flex flex-row items-center justify-between pb-1.5 space-y-0 pt-4 px-4">
              <CardTitle className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/80">{w.title}</CardTitle>
              <w.icon className={`h-3.5 w-3.5 ${w.success ? 'text-emerald-500' : w.danger ? 'text-destructive' : 'text-muted-foreground/60'}`} />
            </CardHeader>
            <CardContent className="pb-4 px-4">
              <div className={`text-xl font-bold tracking-tight ${w.success ? 'text-emerald-600' : w.danger ? 'text-destructive' : 'text-foreground'}`}>
                {w.value}
              </div>
              <p className="text-[10px] font-medium text-muted-foreground/50 mt-0.5">{w.sub}</p>
            </CardContent>
          </Card>
        ))}
      </div>

      <Card className="shadow-none rounded-xl border border-border/40 bg-surface backdrop-blur-md overflow-hidden">
        <CardHeader className="pb-3 border-b border-border/40">
          <CardTitle className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground/80 flex items-center justify-between">
            <span>Sector Agreements & Operational Governance Status</span>
            <span className="text-primary font-mono text-xs">{sectorKycRequests?.length || 0} Sectors Assigned</span>
          </CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          {sectorKycRequests && sectorKycRequests.length > 0 ? (
            <div className="divide-y divide-border/20 text-xs">
              {sectorKycRequests.map((req) => (
                <div key={req.id} className="p-4 flex flex-col md:flex-row items-start md:items-center justify-between gap-4 hover:bg-muted/10 transition-colors">
                  <div className="space-y-1">
                    <div className="flex items-center gap-2">
                      <span className="font-bold text-foreground text-xs">{req.sector.name}</span>
                      <span className="font-mono text-[10px] bg-muted/40 px-2 py-0.5 rounded text-muted-foreground">{req.sector.code}</span>
                    </div>
                    <p className="text-[10px] text-muted-foreground">
                      Assigned Approver: <strong className="text-foreground">{req.assignedApprover?.firstName} {req.assignedApprover?.lastName}</strong> ({req.assignedApprover?.role})
                    </p>
                  </div>

                  <div className="flex items-center gap-3">
                    {req.status === 'APPROVED' && (
                      <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold bg-emerald-500/10 text-emerald-500 border border-emerald-500/20">
                        <CheckCircle className="h-3 w-3" /> Approved & Active
                      </span>
                    )}
                    {req.status === 'UNDER_APPROVAL' && (
                      <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold bg-sky-500/10 text-sky-500 border border-sky-500/20">
                        <Clock className="h-3 w-3" /> Under Review
                      </span>
                    )}
                    {(req.status === 'AGREEMENT_PENDING' || req.status === 'AGREEMENT_ACCEPTED') && (
                      <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold bg-amber-500/10 text-amber-500 border border-amber-500/20">
                        <FileCheck className="h-3 w-3" /> Agreement Pending
                      </span>
                    )}
                    {req.status === 'REJECTED' && (
                      <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold bg-rose-500/10 text-rose-500 border border-rose-500/20">
                        <XCircle className="h-3 w-3" /> Rejected
                      </span>
                    )}
                    {(req.status === 'AGREEMENT_PENDING' || req.status === 'REJECTED') && (
                      <Button
                        size="sm"
                        onClick={() => setActiveModalRequest(req)}
                        className="h-7 text-[11px] font-bold bg-primary text-primary-foreground hover:bg-primary/90 rounded-lg px-3"
                      >
                        Sign & Upload Agreement
                      </Button>
                    )}
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="p-6 text-center text-xs text-muted-foreground">
              No sector KYC assignments recorded.
            </div>
          )}
        </CardContent>
      </Card>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Card className="shadow-none rounded-xl border border-border/40 bg-surface backdrop-blur-md">
          <CardHeader className="pb-2"><CardTitle className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground/80">Regional Enrollment Growth</CardTitle></CardHeader>
          <CardContent className="h-[260px] pb-4"><EnrollmentTrendsChart data={chartData.trends} /></CardContent>
        </Card>

        <Card className="shadow-none rounded-xl border border-border/40 bg-surface backdrop-blur-md">
          <CardHeader className="pb-2"><CardTitle className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground/80">Top Scoped Institute Volumetric Scale</CardTitle></CardHeader>
          <CardContent className="h-[260px] pb-4"><DistrictPerformanceChart data={chartData.institutePerformance} /></CardContent>
        </Card>
      </div>

      {activeModalRequest && (
        <SubmitAgreementModal request={activeModalRequest} onClose={() => setActiveModalRequest(null)} />
      )}

      {isPersonalKycModalOpen && (
        <UploadMyKycModal onClose={() => setIsPersonalKycModalOpen(false)} />
      )}
    </div>
  );
}