'use client';

import React, { useState, useEffect } from 'react';
import { 
  Ticket, 
  Building2, 
  UserCheck, 
  CheckCircle2, 
  TrendingUp, 
  Search, 
  ShoppingBag, 
  Filter, 
  X,
  Loader2 
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useDashboardMetrics } from '@/services/superAdmin/queries';
import { DsoCouponStat, InstituteCouponStat, AdvisorCouponStat } from '@/services/superAdmin/types';

export default function CouponConsumptionView() {
  const [activeTab, setActiveTab] = useState<'dso' | 'institute' | 'advisor'>('dso');
  const [searchInput, setSearchInput] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');

  // Debounce server search trigger (300ms)
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearch(searchInput);
    }, 300);
    return () => clearTimeout(timer);
  }, [searchInput]);

  // Server-side query fetching
  const { data, isLoading, isFetching } = useDashboardMetrics(debouncedSearch);

  const metrics = data?.couponMetrics || {
    totalCoupons: 0,
    assignedToDso: 0,
    assignedToInstitute: 0,
    assignedToAdvisor: 0,
    redeemed: 0,
    activationRate: '0.0',
  };

  const consumption = data?.couponsConsumption || {
    dsoBreakdown: [],
    instituteBreakdown: [],
    careerAdvisorBreakdown: [],
  };

  console.log("consumption:", consumption)

  return (
    <div className="space-y-6">
      {/* HEADER SECTION */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 pb-4 border-b border-border/40">
        <div>
          <h2 className="text-md font-black tracking-wider uppercase text-foreground flex items-center gap-2">
            <Ticket className="h-5 w-5 text-primary" /> Coupon Consumption Matrix
          </h2>
          <p className="text-xs text-muted-foreground">
            Dynamic server-side tracking across DSOs, Institutes, and Career Advisor redemptions.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="dark" size="sm" className="h-8 text-xs font-bold uppercase gap-1.5 cursor-pointer">
            <Filter className="h-3.5 w-3.5" /> Export Report
          </Button>
        </div>
      </div>

      {/* KPI METRICS GRID */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
        {[
          { title: "Total Master Coupons", value: metrics.totalCoupons, sub: "Central System Pool", icon: Ticket, color: "text-blue-500" },
          { title: "DSO Inventory", value: metrics.assignedToDso, sub: "Allocated to DSOs", icon: ShoppingBag, color: "text-amber-500" },
          { title: "Institute Pool", value: metrics.assignedToInstitute, sub: "Ready for Advisors", icon: Building2, color: "text-indigo-500" },
          { title: "Advisor Holding", value: metrics.assignedToAdvisor, sub: "Active Field Pipeline", icon: UserCheck, color: "text-purple-500" },
          { title: "Activated / Redeemed", value: metrics.redeemed, sub: `${metrics.activationRate}% Conversion Rate`, icon: CheckCircle2, color: "text-emerald-500", highlight: true }
        ].map((kpi, idx) => (
          <Card key={idx} className={`shadow-none rounded-xl border border-border/40 bg-surface ${kpi.highlight ? 'border-l-4 border-l-emerald-500 bg-emerald-500/5' : ''}`}>
            <CardHeader className="flex flex-row items-center justify-between pb-1 space-y-0 pt-3 px-3.5">
              <CardTitle className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">{kpi.title}</CardTitle>
              <kpi.icon className={`h-4 w-4 ${kpi.color}`} />
            </CardHeader>
            <CardContent className="pb-3 px-3.5">
              <div className="text-xl font-extrabold tracking-tight text-foreground">{kpi.value}</div>
              <p className="text-[10px] font-medium text-muted-foreground mt-0.5">{kpi.sub}</p>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* CONTROLS AND SEARCH */}
      <div className="flex flex-col sm:flex-row justify-between items-stretch sm:items-center gap-3 bg-surface p-2 rounded-xl border border-border/30">
        <div className="flex flex-wrap gap-1.5">
          <Button
            onClick={() => setActiveTab('dso')}
            variant={activeTab === 'dso' ? 'dark' : 'ghost'}
            className="h-8 text-xs font-bold uppercase tracking-wider rounded-lg px-3 cursor-pointer"
          >
            DSO Allocation ({consumption.dsoBreakdown.length})
          </Button>
          <Button
            onClick={() => setActiveTab('institute')}
            variant={activeTab === 'institute' ? 'dark' : 'ghost'}
            className="h-8 text-xs font-bold uppercase tracking-wider rounded-lg px-3 cursor-pointer"
          >
            Institute Sales ({consumption.instituteBreakdown.length})
          </Button>
          <Button
            onClick={() => setActiveTab('advisor')}
            variant={activeTab === 'advisor' ? 'dark' : 'ghost'}
            className="h-8 text-xs font-bold uppercase tracking-wider rounded-lg px-3 cursor-pointer"
          >
            Career Advisor Redemptions ({consumption.careerAdvisorBreakdown.length})
          </Button>
        </div>

        {/* SERVER SEARCH INPUT */}
        <div className="relative max-w-xs w-full">
          {isFetching ? (
            <Loader2 className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-primary animate-spin" />
          ) : (
            <Search className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground" />
          )}
          <Input
            placeholder="Server Search Name, Code, Email..."
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            className="h-8 text-xs pl-8 pr-8 bg-background border-border/60 rounded-lg"
          />
          {searchInput && (
            <button 
              onClick={() => setSearchInput('')}
              className="absolute right-2.5 top-2.5 text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
            >
              <X className="h-3.5 w-3.5" />
            </button>
          )}
        </div>
      </div>

      {/* TAB 1: DSO BREAKDOWN */}
      {activeTab === 'dso' && (
        <Card className="shadow-none rounded-xl border border-border/40">
          <CardHeader className="pb-3">
            <CardTitle className="text-xs font-bold uppercase tracking-wider text-foreground">District Sector Owner (DSO) Breakdown</CardTitle>
            <CardDescription className="text-[11px]">Server queries executed against DSO partners.</CardDescription>
          </CardHeader>
          <CardContent className="px-0 pb-0">
            <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/40 text-[10px] uppercase font-bold text-muted-foreground tracking-wider">
                    <th className="p-3 pl-4">DSO Partner</th>
                    <th className="p-3 pl-4">Regional Authorized</th>
                    <th className="p-3">Email Contact</th>
                    <th className="p-3 text-center">Allocated</th>
                    <th className="p-3 text-center">Redeemed</th>
                    <th className="p-3 text-center">PO Quantity</th>
                    <th className="p-3 text-right pr-4">Efficiency</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border/30 font-medium">
                  {consumption.dsoBreakdown.length > 0 ? (
                    consumption.dsoBreakdown.map((row: DsoCouponStat) => (
                      <tr key={row.id} className="hover:bg-muted/20 transition-colors">
                        <td className="p-3 pl-4 font-bold text-foreground">{row.name}</td>
                        <td className="p-3 text-muted-foreground">{row.region}</td>
                        <td className="p-3 text-muted-foreground">{row.email}</td>
                        <td className="p-3 text-center font-semibold text-foreground">{row.allocatedCoupons}</td>
                        <td className="p-3 text-center text-emerald-600 font-bold">{row.redeemedCoupons}</td>
                        <td className="p-3 text-center text-amber-600 font-semibold">{row.poRequested} units</td>
                        <td className="p-3 text-right pr-4 font-bold text-foreground">
                          <span className="inline-flex items-center gap-1 bg-emerald-500/10 text-emerald-600 px-2 py-0.5 rounded-full text-[10px]">
                            <TrendingUp className="h-3 w-3" /> {row.activationRate}%
                          </span>
                        </td>
                      </tr>
                    ))
                  ) : (
                    <tr>
                      <td colSpan={6} className="p-8 text-center text-xs text-muted-foreground">
                        {isLoading ? 'Fetching records...' : debouncedSearch ? `No DSO records found for "${debouncedSearch}"` : 'No DSO data found.'}
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>
      )}

      {/* TAB 2: INSTITUTE BREAKDOWN */}
      {activeTab === 'institute' && (
        <Card className="shadow-none rounded-xl border border-border/40">
          <CardHeader className="pb-3">
            <CardTitle className="text-xs font-bold uppercase tracking-wider text-foreground">Institute Sales Leaderboard</CardTitle>
            <CardDescription className="text-[11px]">Server queries executed against Institutes.</CardDescription>
          </CardHeader>
          <CardContent className="px-0 pb-0">
            <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/40 text-[10px] uppercase font-bold text-muted-foreground tracking-wider">
                    <th className="p-3 pl-4">Institute Entity</th>
                    <th className="p-3">Code</th>
                    <th className="p-3 text-center">Advisor Network</th>
                    <th className="p-3 text-center">Direct Inventory</th>
                    <th className="p-3 text-center">Assigned to CAs</th>
                    <th className="p-3 text-center">Student Activations</th>
                    <th className="p-3 text-right pr-4">Conversion Rate</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border/30 font-medium">
                  {consumption.instituteBreakdown.length > 0 ? (
                    consumption.instituteBreakdown.map((row: InstituteCouponStat) => (
                      <tr key={row.id} className="hover:bg-muted/20 transition-colors">
                        <td className="p-3 pl-4 font-bold text-foreground">{row.name}</td>
                        <td className="p-3 text-muted-foreground font-mono">{row.code}</td>
                        <td className="p-3 text-center text-foreground font-semibold">{row.advisorsCount} CAs</td>
                        <td className="p-3 text-center text-indigo-600 font-semibold">{row.directInventory}</td>
                        <td className="p-3 text-center text-purple-600 font-bold">{row.assignedToAdvisors}</td>
                        <td className="p-3 text-center text-emerald-600 font-bold">{row.activatedByStudents}</td>
                        <td className="p-3 text-right pr-4 font-bold text-foreground">
                          <span className="inline-flex items-center gap-1 bg-indigo-500/10 text-indigo-600 px-2 py-0.5 rounded-full text-[10px]">
                            {row.conversionRate}%
                          </span>
                        </td>
                      </tr>
                    ))
                  ) : (
                    <tr>
                      <td colSpan={7} className="p-8 text-center text-xs text-muted-foreground">
                        {isLoading ? 'Fetching records...' : debouncedSearch ? `No Institutes found for "${debouncedSearch}"` : 'No Institute data found.'}
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>
      )}

      {/* TAB 3: CAREER ADVISOR BREAKDOWN */}
      {activeTab === 'advisor' && (
        <Card className="shadow-none rounded-xl border border-border/40">
          <CardHeader className="pb-3">
            <CardTitle className="text-xs font-bold uppercase tracking-wider text-foreground">Career Advisor Field Redemptions</CardTitle>
            <CardDescription className="text-[11px]">Server queries executed against Career Advisors.</CardDescription>
          </CardHeader>
          <CardContent className="px-0 pb-0">
            <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/40 text-[10px] uppercase font-bold text-muted-foreground tracking-wider">
                    <th className="p-3 pl-4">Career Advisor</th>
                    <th className="p-3">Code</th>
                    <th className="p-3">Parent Institute</th>
                    <th className="p-3 text-center">Allocated</th>
                    <th className="p-3 text-center">Redeemed</th>
                    <th className="p-3 text-right pr-4">Activation Rate</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border/30 font-medium">
                  {consumption.careerAdvisorBreakdown.length > 0 ? (
                    consumption.careerAdvisorBreakdown.map((row: AdvisorCouponStat) => (
                      <tr key={row.id} className="hover:bg-muted/20 transition-colors">
                        <td className="p-3 pl-4 font-bold text-foreground">{row.name}</td>
                        <td className="p-3 text-muted-foreground font-mono">{row.code}</td>
                        <td className="p-3 text-foreground">{row.instituteName}</td>
                        <td className="p-3 text-center font-semibold text-foreground">{row.allocated}</td>
                        <td className="p-3 text-center font-bold text-emerald-600">{row.redeemed}</td>
                        <td className="p-3 text-right pr-4 font-bold text-foreground">
                          <span className="inline-flex items-center gap-1 bg-emerald-500/10 text-emerald-600 px-2 py-0.5 rounded-full text-[10px]">
                            {row.activationRate}%
                          </span>
                        </td>
                      </tr>
                    ))
                  ) : (
                    <tr>
                      <td colSpan={6} className="p-8 text-center text-xs text-muted-foreground">
                        {isLoading ? 'Fetching records...' : debouncedSearch ? `No Career Advisors found for "${debouncedSearch}"` : 'No Career Advisor data found.'}
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}