'use client';

import React, { useState } from 'react';
import { 
  Users, GraduationCap, Award, Plus, AlertTriangle, 
  CheckCircle, Clock, FileCheck, XCircle 
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { useDashboardMetrics } from '@/services/superAdmin/queries';
import { useMyInstituteKycRequests } from '@/services/instituteKyc/queries';
import { InstituteKycRequestItem } from '@/services/instituteKyc/api';
import SubmitInstituteAgreementModal from './SubmitInstituteAgreementModal';


interface Props {
  userContext: any;
}

export default function InstituteAdminView({ userContext }: Props) {
  const { data: metrics, isError, isLoading: isMetricsLoading } = useDashboardMetrics();
  const { data: instituteKycRequests, isLoading: isKycLoading } = useMyInstituteKycRequests();

  const [activeModalRequest, setActiveModalRequest] = useState<InstituteKycRequestItem | null>(null);

  // Filter pending Institute KYCs requiring Institute Admin action
  const pendingActionRequests = instituteKycRequests?.filter(
    (r: any) => r.status === 'AGREEMENT_PENDING' || r.status === 'REJECTED'
  );

  if (isMetricsLoading || isKycLoading) {
    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(4)].map((_, i) => (
          <div key={i} className="h-24 bg-muted/20 rounded-xl border border-border/10" />
        ))}
      </div>
    );
  }

  if (isError || !metrics?.widgets) return null;

  const { managedAdvisors, verifyAdvisors, activeLeads, totalAdmissions } = metrics.widgets;

  return (
    <div className="space-y-6 max-w-7xl mx-auto animate-in fade-in duration-300 select-none">
      
      {/* HEADER COMPONENT */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 border-b border-border/10 pb-5">
        <div className="flex flex-col gap-0.5">
          <h1 className="text-lg font-bold tracking-tight text-foreground uppercase">
            Center Operations Desk
          </h1>
          <p className="text-[11px] font-medium text-muted-foreground/80">
            Physical facility local operations engine workspace • Welcome back, {userContext?.firstName} {userContext?.lastName}.
          </p>
        </div>
        <Button className="h-8 text-xs font-semibold gap-1.5 transition-transform active:scale-95">
          <Plus className="h-3.5 w-3.5 stroke-[2.5]" /> Add Field Advisor
        </Button>
      </div>

      {/* 🌟 1. ACTION REQUIRED BANNER (If Institute Admin has pending agreement tasks) */}
      {pendingActionRequests && pendingActionRequests.length > 0 && (
        <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: {pendingActionRequests.length} Pending Institute Agreement(s)
              </h3>
              <p className="text-[11px] font-medium text-amber-200/80">
                Your institute node requires a signed agreement upload before operational activation.
              </p>
            </div>
          </div>
        </div>
      )}

      {/* METRIC CARDS GRID */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {/* Staff Strength / Managed Advisors */}
        <Card className="shadow-sm rounded-xl border border-border/40 bg-card/40">
          <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
            <CardTitle className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
              Staff Strength
            </CardTitle>
            <Users className="h-4 w-4 text-primary" />
          </CardHeader>
          <CardContent>
            <div className="text-xl font-bold text-foreground">
              {managedAdvisors ?? 0}
            </div>
            <p className="text-[10px] text-muted-foreground/60 mt-0.5">
              Advisors tied to this local center node
            </p>
          </CardContent>
        </Card>

        {/* Pending Advisor Verification */}
        <Card className="shadow-sm rounded-xl border border-border/40 bg-card/40">
          <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
            <CardTitle className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
              Pending Advisor Verification
            </CardTitle>
            <Users className="h-4 w-4 text-primary" />
          </CardHeader>
          <CardContent>
            <div className="text-xl font-bold text-foreground">
              {verifyAdvisors ?? 0}
            </div>
            <p className="text-[10px] text-muted-foreground/60 mt-0.5">
              Advisors awaiting center verification
            </p>
          </CardContent>
        </Card>

        {/* Inbound Leads / Active Leads */}
        <Card className="shadow-sm rounded-xl border border-border/40 bg-card/40">
          <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
            <CardTitle className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
              Inbound Leads
            </CardTitle>
            <GraduationCap className="h-4 w-4 text-primary" />
          </CardHeader>
          <CardContent>
            <div className="text-xl font-bold text-foreground">
              {activeLeads ?? 0}
            </div>
            <p className="text-[10px] text-muted-foreground/60 mt-0.5">
              Students awaiting profiling loops
            </p>
          </CardContent>
        </Card>

        {/* Confirmed Admissions / Total Admissions */}
        <Card className="shadow-sm rounded-xl border border-border/40 bg-card/40 border-l-primary border-l-2">
          <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
            <CardTitle className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
              Confirmed Admissions
            </CardTitle>
            <Award className="h-4 w-4 text-primary" />
          </CardHeader>
          <CardContent>
            <div className="text-xl font-bold text-foreground">
              {totalAdmissions ?? 0}
            </div>
            <p className="text-[10px] text-muted-foreground/60 mt-0.5">
              Successful placement transformations
            </p>
          </CardContent>
        </Card>
      </div>

      {/* 🌟 2. INSTITUTE KYC / AGREEMENT STATUS TABLE */}
      <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>Institute Agreement & Operational Governance Status</span>
            <span className="text-primary font-mono text-xs">
              {instituteKycRequests?.length || 0} Institute Node(s)
            </span>
          </CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          {instituteKycRequests && instituteKycRequests.length > 0 ? (
            <div className="divide-y divide-border/20 text-xs">
              {instituteKycRequests.map((req: any) => (
                <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.institute.name}</span>
                      <span className="font-mono text-[10px] bg-muted/40 px-2 py-0.5 rounded text-muted-foreground">
                        {req.institute.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">
                    {/* STATUS BADGES */}
                    {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>
                    )}

                    {/* ACTION BUTTON */}
                    {(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 institute KYC or agreement records mapped to this account.
            </div>
          )}
        </CardContent>
      </Card>

      {/* AGREEMENT EXECUTION MODAL */}
      {activeModalRequest && (
        <SubmitInstituteAgreementModal
          request={activeModalRequest}
          onClose={() => setActiveModalRequest(null)}
        />
      )}

    </div>
  );
}