'use client';

import React, { useState, useEffect } from 'react';
import { 
  Layers, 
  Map, 
  Home, 
  UserCheck, 
  Users, 
  TrendingUp, 
  Radio, 
  Download, 
  PlusCircle, 
  Ticket, 
  ShieldAlert,
  BookOpen,
  Search,
  ChevronDown,
  ChevronRight,
  ChevronLeft
} 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, useGlobalBroadcast } from '@/services/superAdmin/queries';
import { 
  EnrollmentTrendsChart, 
  DistrictPerformanceChart, 
  SectorGrowthChart, 
  ConversionFunnelChart 
} from '@/components/dashboard/charts';
import { reportsApi } from '@/services/reports/api';
import CreateDistrictModal from '../../districts/_components/CreateDistrictModal';
import CreateSectorModal from '../../sectors/_components/CreateSectorModal';
import CreateStateModal from '../../states/_components/CreateStateModal';
import CouponConsumptionView from './CouponConsumptionView';

interface Props {
  userContext: any;
}

export default function AdminView({ userContext }: Props) {
  const [viewMode, setViewMode] = useState<'matrix' | 'coupons' | 'district-sectors'>('matrix');
  const [isStateModalOpen, setIsStateModalOpen] = useState(false);
  const [isDistrictModalOpen, setIsDistrictModalOpen] = useState(false);
  const [isSectorModalOpen, setIsSectorModalOpen] = useState(false);

  // Dynamic Backend Search & Debounce States
  const [searchInput, setSearchInput] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const [expandedDistricts, setExpandedDistricts] = useState<Record<string, boolean>>({});

  // Debounce user typing by 400ms to avoid unnecessary API calls
  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedSearch(searchInput.trim());
    }, 400);
    return () => clearTimeout(handler);
  }, [searchInput]);

  // Fetch Dashboard Metrics using Backend Dynamic Search Query
  const { data: metrics, isLoading, isError } = useDashboardMetrics(debouncedSearch);
  const broadcastMutation = useGlobalBroadcast();

  const toggleDistrictAccordion = (id: string) => {
    setExpandedDistricts((prev) => ({ ...prev, [id]: !prev[id] }));
  };

  const chartData = {
    districtPerformance: metrics?.charts?.districtPerformance || [],
    trends: 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 triggerFileDownloadStream = async (type: 'excel' | 'pdf') => {
    try {
      toast.loading(`Compiling export binary stream data...`, { id: 'report-dl' });
      await reportsApi.downloadReport({ type, module: 'dso' });
      toast.success('Document downloaded successfully.', { id: 'report-dl' });
    } catch (err) {
      toast.error('Download failed. Pipeline validation error.', { id: 'report-dl' });
    }
  };

  const handleBroadcastSimulation = () => {
    broadcastMutation.mutate({
      targetChannel: 'IN_APP',
      broadcastTitle: 'System Security Alert',
      broadcastMessage: 'System optimization sequence active. Secure configurations updated.',
    });
  };

  if (isLoading) {
    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>
    );
  }

  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 system topological metrics data models. Please check access tokens.
      </div>
    );
  }

  return (
    <>
    <div className="space-y-6 max-w-7xl mx-auto animate-in fade-in duration-300">
      {/* GLOBAL VIEW TOGGLE HEADER */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 border-b border-border/40 pb-4">
        <div>
          <h1 className="text-sm font-black tracking-widest text-foreground uppercase">
            SUPER ADMIN ENTERPRISE MATRIX
          </h1>
          <p className="text-[11px] font-medium text-muted-foreground/70">
            National Scaling Ecosystem Topologies & Governance Management
          </p>
        </div>

        <div className="flex flex-wrap items-center gap-2">
          <div className="bg-muted/40 p-1 rounded-lg border border-border/50 flex gap-1">
            <Button
              onClick={() => setViewMode('matrix')}
              variant={viewMode === 'matrix' ? 'dark' : 'ghost'}
              className="h-7 text-[10px] font-bold uppercase tracking-wider px-2.5 rounded-md"
            >
              System Overview
            </Button>
            <Button
              onClick={() => setViewMode('district-sectors')}
              variant={viewMode === 'district-sectors' ? 'dark' : 'ghost'}
              className="h-7 text-[10px] font-bold uppercase tracking-wider px-2.5 rounded-md gap-1"
            >
              <Map className="h-3 w-3" /> District Sectors & Courses
            </Button>
            <Button
              onClick={() => setViewMode('coupons')}
              variant={viewMode === 'coupons' ? 'dark' : 'ghost'}
              className="h-7 text-[10px] font-bold uppercase tracking-wider px-2.5 rounded-md gap-1"
            >
              <Ticket className="h-3 w-3" /> Coupon Consumption
            </Button>
          </div>

          <Button
            onClick={handleBroadcastSimulation}
            disabled={broadcastMutation.isPending}
            className="h-8 rounded-md px-3 text-[11px] font-bold tracking-wider uppercase gap-1.5 bg-foreground text-background hover:bg-foreground/90 cursor-pointer"
          >
            <Radio className="h-3 w-3 stroke-[3]" />
            <span>{broadcastMutation.isPending ? 'Broadcasting...' : 'Global Broadcast'}</span>
          </Button>
          <Button
            onClick={() => triggerFileDownloadStream('pdf')}
            variant="outline"
            className="h-8 rounded-md px-3 text-[11px] font-bold tracking-wider uppercase gap-1.5 border-border/80 hover:bg-muted/60 text-foreground cursor-pointer"
          >
            <Download className="h-3 w-3" />
            <span>Export Analytics</span>
          </Button>
        </div>
      </div>

      {/* DYNAMIC VIEW MODES */}
      {viewMode === 'coupons' ? (
        <CouponConsumptionView />
      ) : viewMode === 'district-sectors' ? (
        <div className="space-y-6">
          {/* SEARCH BAR FOR DYNAMIC BACKEND QUERYING */}
          <div className="bg-surface border border-border/40 rounded-xl p-3 flex flex-col sm:flex-row items-center justify-between gap-3">
            <div className="flex items-center gap-2 text-xs font-bold text-muted-foreground uppercase">
              <Search className="h-4 w-4 text-primary" /> Dynamic Backend Query Engine
            </div>
            <div className="relative w-full sm:w-80">
              <Search className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground" />
              <input
                type="text"
                placeholder="Search Districts, Sectors, or Courses..."
                value={searchInput}
                onChange={(e) => setSearchInput(e.target.value)}
                className="w-full pl-8 pr-3 py-1.5 text-xs bg-background border border-border/50 rounded-lg focus:outline-none focus:border-primary"
              />
            </div>
          </div>

          {/* DYNAMIC DISTRICT SECTOR MATRIX TABLE */}
          <Card className="border border-border/40 shadow-none rounded-xl">
            <CardHeader className="pb-3">
              <CardTitle className="text-xs font-bold uppercase tracking-wider flex items-center gap-2">
                <Map className="h-4 w-4 text-primary" /> District & Sector Activations Matrix
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs border-collapse">
                  <thead>
                    <tr className="border-b border-border/40 bg-muted/30 text-[10px] uppercase text-muted-foreground font-bold">
                      <th className="p-2.5 w-8"></th>
                      <th className="p-2.5">District</th>
                      <th className="p-2.5">Active / Total Sectors</th>
                      <th className="p-2.5">Assigned Coupons</th>
                      <th className="p-2.5">Activated Coupons</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border/20">
                    {metrics.districtSectorMetrics?.length ? (
                      metrics.districtSectorMetrics.map((item) => {
                        const isExpanded = !!expandedDistricts[item.districtId];
                        return (
                          <React.Fragment key={item.districtId}>
                            <tr
                              onClick={() => toggleDistrictAccordion(item.districtId)}
                              className="hover:bg-muted/20 transition-colors cursor-pointer"
                            >
                              <td className="p-2.5 text-muted-foreground">
                                {isExpanded ? (
                                  <ChevronDown className="h-3.5 w-3.5 text-primary" />
                                ) : (
                                  <ChevronRight className="h-3.5 w-3.5" />
                                )}
                              </td>
                              <td className="p-2.5 font-bold">
                                {item.districtName} ({item.districtCode})
                              </td>
                              <td className="p-2.5">
                                <span className="font-semibold text-emerald-600">
                                  {item.activeSectors}
                                </span>{' '}
                                / {item.totalSectors}
                              </td>
                              <td className="p-2.5 font-semibold">{item.assignedCoupons}</td>
                              <td className="p-2.5 font-bold text-emerald-600">
                                {item.activatedCoupons}
                              </td>
                            </tr>

                            {/* ACCORDION EXPANDED SECTOR MATRIX */}
                            {isExpanded && (
                              <tr>
                                <td colSpan={5} className="p-0 bg-muted/10 border-b border-border/30">
                                  <div className="p-3 pl-10 space-y-2">
                                    <div className="text-[10px] uppercase font-bold text-muted-foreground tracking-wider mb-1">
                                      Associated Sectors ({item.sectorsBreakdown.length})
                                    </div>
                                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
                                      {item.sectorsBreakdown.map((s) => (
                                        <div
                                          key={s.sectorId}
                                          className="p-2 bg-background border border-border/40 rounded-md text-[11px] flex items-center justify-between"
                                        >
                                          <div className="flex items-center gap-2 overflow-hidden">
                                            <span
                                              className={`h-2 w-2 rounded-full flex-shrink-0 ${
                                                s.isActive ? 'bg-emerald-500' : 'bg-muted-foreground/30'
                                              }`}
                                            />
                                            <span className="font-medium truncate">{s.sectorName}</span>
                                          </div>
                                          <span className="text-[10px] font-semibold text-muted-foreground bg-muted/50 px-1.5 py-0.5 rounded">
                                            {s.activatedCoupons}/{s.assignedCoupons}
                                          </span>
                                        </div>
                                      ))}
                                    </div>
                                  </div>
                                </td>
                              </tr>
                            )}
                          </React.Fragment>
                        );
                      })
                    ) : (
                      <tr>
                        <td colSpan={5} className="p-4 text-center text-xs text-muted-foreground">
                          No matching district sector data found.
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>

          {/* DYNAMIC COURSE REDEMPTION TABLE */}
          <Card className="border border-border/40 shadow-none rounded-xl">
            <CardHeader className="pb-3">
              <CardTitle className="text-xs font-bold uppercase tracking-wider flex items-center gap-2">
                <BookOpen className="h-4 w-4 text-primary" /> Top Course Coupon Activation & Redemptions
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs border-collapse">
                  <thead>
                    <tr className="border-b border-border/40 bg-muted/30 text-[10px] uppercase text-muted-foreground font-bold">
                      <th className="p-2.5">Course Code</th>
                      <th className="p-2.5">Course Name</th>
                      <th className="p-2.5">Associated Sector</th>
                      <th className="p-2.5">Fees</th>
                      <th className="p-2.5">Total Coupon Redemptions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border/20">
                    {metrics.courseCouponMetrics?.length ? (
                      metrics.courseCouponMetrics.map((c) => (
                        <tr key={c.courseId} className="hover:bg-muted/10 transition-colors">
                          <td className="p-2.5 font-mono text-[11px] font-bold">{c.courseCode}</td>
                          <td className="p-2.5 font-bold">{c.courseName}</td>
                          <td className="p-2.5 text-muted-foreground">{c.sectorName}</td>
                          <td className="p-2.5 font-medium">{c.fees ? `₹${c.fees}` : 'Free / Unset'}</td>
                          <td className="p-2.5 font-bold text-emerald-600">{c.totalRedemptions}</td>
                        </tr>
                      ))
                    ) : (
                      <tr>
                        <td colSpan={5} className="p-4 text-center text-xs text-muted-foreground">
                          No matching course records found.
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </div>
      ) : (
        <>
          {/* SYSTEM SUMMARY METRICS GRID */}
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
            {[
              { title: 'Ecosystem States', value: metrics.widgets.totalStates, sub: 'Configured Target Nodes', icon: Home },
              { title: 'Active Districts', value: `${metrics.widgets.totalDistricts} / 36`, sub: 'Geographic Scale Operations', icon: Map },
              { title: 'Functional Sectors', value: metrics.widgets.totalSectors, sub: 'Monitored Scope', icon: Layers },
              { title: 'Managed Institutes', value: metrics.widgets.totalInstitutes, sub: 'Verification Points', icon: Home },
              { title: 'Career Advisors Pool', value: metrics.widgets.totalCareerAdvisors, sub: 'Active Operations Layer', icon: UserCheck, highlight: true },
              { title: 'Registered Candidates', value: metrics.widgets.totalStudents, sub: 'Total Funnel Pipeline', icon: Users },
              { title: 'Today\'s Influx', value: metrics.widgets.todayRegistrations || 0, sub: 'New Student Registrations Today', icon: TrendingUp, success: true },
              {
                title: 'KYC Pending Action',
                value: metrics.widgets.pendingApprovals || 0,
                sub: `User: ${metrics.widgets.kycBreakdown?.userKyc || 0} | Sector: ${metrics.widgets.kycBreakdown?.sectorKyc || 0} | Inst: ${metrics.widgets.kycBreakdown?.instituteKyc || 0}`,
                icon: ShieldAlert,
                danger: (metrics.widgets.pendingApprovals ?? 0) > 0,
              },
            ].map((w, idx) => (
              <Card
                key={idx}
                className={`bg-surface/90 shadow-none rounded-xl border border-border/40 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">
                    {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 mt-0.5">{w.sub}</p>
                </CardContent>
              </Card>
            ))}
          </div>

          {/* QUICK TOPOLOGY CONTROLS */}
          <div className="bg-surface border border-border/40 rounded-xl p-4 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <div className="space-y-0.5">
              <h3 className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
                Quick Topology Controls
              </h3>
              <p className="text-[11px] text-muted-foreground">Programmatically seed structures into the administrative grid.</p>
            </div>
            <div className="flex flex-wrap gap-2">
              <button
                onClick={() => setIsStateModalOpen(true)}
                className="flex items-center gap-1.5 text-[11px] font-bold uppercase tracking-wider border border-border/50 bg-background px-3 py-1.5 rounded-lg hover:bg-muted transition-all text-foreground shadow-sm cursor-pointer"
              >
                <PlusCircle className="h-3.5 w-3.5 text-muted-foreground" /> State Node
              </button>
              <button
                onClick={() => setIsDistrictModalOpen(true)}
                className="flex items-center gap-1.5 text-[11px] font-bold uppercase tracking-wider border border-border/50 bg-background px-3 py-1.5 rounded-lg hover:bg-muted transition-all text-foreground shadow-sm cursor-pointer"
              >
                <PlusCircle className="h-3.5 w-3.5 text-muted-foreground" /> District Node
              </button>
              <button
                onClick={() => setIsSectorModalOpen(true)}
                className="flex items-center gap-1.5 text-[11px] font-bold uppercase tracking-wider border border-border/50 bg-background px-3 py-1.5 rounded-lg hover:bg-muted transition-all text-foreground shadow-sm cursor-pointer"
              >
                <PlusCircle className="h-3.5 w-3.5 text-muted-foreground" /> Sector Node
              </button>
            </div>
          </div>

          {/* ANALYTICAL CHARTS GRID */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card className="shadow-none rounded-xl border border-border/40 bg-card">
              <CardHeader className="pb-2">
                <CardTitle className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
                  Enrollment Growth Analysis
                </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-card">
              <CardHeader className="pb-2">
                <CardTitle className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
                  District Top Performance Volume
                </CardTitle>
              </CardHeader>
              <CardContent className="h-[260px] pb-4">
                <DistrictPerformanceChart data={chartData.districtPerformance} />
              </CardContent>
            </Card>

            <Card className="shadow-none rounded-xl border border-border/40 bg-card">
              <CardHeader className="pb-2">
                <CardTitle className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
                  Operational Sector Activation Pace
                </CardTitle>
              </CardHeader>
              <CardContent className="h-[260px] pb-4">
                <SectorGrowthChart data={chartData.trends} />
              </CardContent>
            </Card>

            <Card className="shadow-none rounded-xl border border-border/40 bg-card">
              <CardHeader className="pb-2">
                <CardTitle className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
                  Lifecycle Acquisition Funnel Conversion
                </CardTitle>
              </CardHeader>
              <CardContent className="h-[260px] pb-4 flex items-center justify-center">
                <ConversionFunnelChart data={chartData.funnel} />
              </CardContent>
            </Card>
          </div>
        </>
      )}


    </div>

      {/* TOPOLOGY MODALS */}
      {isStateModalOpen && <CreateStateModal onClose={() => setIsStateModalOpen(false)} />}
      {isDistrictModalOpen && <CreateDistrictModal onClose={() => setIsDistrictModalOpen(false)} />}
      {isSectorModalOpen && <CreateSectorModal onClose={() => setIsSectorModalOpen(false)} />}
    </>
  );
}