import React, { useState, useEffect, useMemo } from 'react';
import { 
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Cell, PieChart, Pie, Legend
} from 'recharts';
import { 
  Users, Clock, Phone, TrendingUp, Filter
} from 'lucide-react';
import { getAttendances, getUsers, getTeams } from '../services/dataService';
import { COLORS } from '../constants';
import { Attendance, DashboardFilter, FunnelStage, User } from '../types';
import { KPICard } from '../components/KPICard';
import { DateRangePicker } from '../components/DateRangePicker';
import { SellersTable } from '../components/SellersTable';
import { ProductLists } from '../components/ProductLists';

// Interface for seller statistics accumulator
interface SellerStats {
  total: number;
  converted: number;
  scoreSum: number;
  count: number;
  timeSum: number;
}

export const Dashboard: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<Attendance[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [teams, setTeams] = useState<any[]>([]);
  
  const [filters, setFilters] = useState<DashboardFilter>({
    dateRange: {
      start: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), // Last 30 days
      end: new Date(),
    },
    userId: 'all',
    teamId: 'all',
  });

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const tenantId = localStorage.getItem('ctms_tenant_id');
        if (!tenantId) return;

        // Fetch users, attendances and teams in parallel
        const [fetchedUsers, fetchedData, fetchedTeams] = await Promise.all([
          getUsers(tenantId),
          getAttendances(tenantId, filters),
          getTeams(tenantId)
        ]);
        
        setUsers(fetchedUsers);
        setData(fetchedData);
        setTeams(fetchedTeams);
      } catch (error) {
        console.error("Error loading dashboard data:", error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [filters]);

  // --- Metrics Calculations ---
  const totalLeads = data.length;
  const avgScore = data.length > 0 ? (data.reduce((acc, curr) => acc + curr.score, 0) / data.length).toFixed(1) : "0";
  const avgResponseTime = data.length > 0 ? (data.reduce((acc, curr) => acc + curr.first_response_time_min, 0) / data.length).toFixed(0) : "0";
  const avgHandleTime = data.length > 0 ? (data.reduce((acc, curr) => acc + curr.handling_time_min, 0) / data.length).toFixed(0) : "0";
  
  // --- Chart Data: Funnel ---
  const funnelData = useMemo(() => {
    const stagesOrder = [
      FunnelStage.NO_CONTACT, 
      FunnelStage.IDENTIFICATION, 
      FunnelStage.NEGOTIATION, 
      FunnelStage.WON, 
      FunnelStage.LOST
    ];
    
    const counts = data.reduce((acc, curr) => {
      acc[curr.funnel_stage] = (acc[curr.funnel_stage] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    return stagesOrder.map(stage => ({
      name: stage,
      value: counts[stage] || 0
    }));
  }, [data]);

  // --- Chart Data: Origin ---
  const originData = useMemo(() => {
    const origins = data.reduce((acc, curr) => {
      acc[curr.origin] = (acc[curr.origin] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    // Ensure type safety for value in sort
    return (Object.entries(origins) as [string, number][])
      .map(([name, value]) => ({ name, value }))
      .sort((a, b) => b.value - a.value);
  }, [data]);

  // --- Table Data: Sellers Ranking ---
  const sellersRanking = useMemo(() => {
    const stats = data.reduce<Record<string, SellerStats>>((acc, curr) => {
      if (!acc[curr.user_id]) {
        acc[curr.user_id] = { total: 0, converted: 0, scoreSum: 0, count: 0, timeSum: 0 };
      }
      acc[curr.user_id].total += 1;
      if (curr.converted) acc[curr.user_id].converted += 1;
      acc[curr.user_id].scoreSum += curr.score;
      acc[curr.user_id].timeSum += curr.first_response_time_min;
      acc[curr.user_id].count += 1;
      return acc;
    }, {});

    return Object.entries(stats)
      .map(([userId, s]) => {
        const stat = s as SellerStats;
        const user = users.find(u => u.id === userId);
        if (!user) return null;
        return {
          user,
          total: stat.total,
          avgScore: (stat.scoreSum / stat.count).toFixed(1),
          conversionRate: ((stat.converted / stat.total) * 100).toFixed(1),
          responseTime: (stat.timeSum / stat.count).toFixed(0)
        };
      })
      .filter((item): item is NonNullable<typeof item> => item !== null);
  }, [data, users]);

  // --- Lists Data: Products ---
  const productStats = useMemo(() => {
    const requested: Record<string, number> = {};
    const sold: Record<string, number> = {};

    data.forEach(d => {
      if (d.product_requested) requested[d.product_requested] = (requested[d.product_requested] || 0) + 1;
      if (d.product_sold) sold[d.product_sold] = (sold[d.product_sold] || 0) + 1;
    });

    const formatList = (record: Record<string, number>, total: number) => 
      Object.entries(record)
        .map(([name, count]) => ({ name, count, percentage: Math.round((count / (total || 1)) * 100) }))
        .sort((a, b) => b.count - a.count)
        .slice(0, 5);

    const totalReq = Object.values(requested).reduce((a, b) => a + b, 0);
    const totalSold = Object.values(sold).reduce((a, b) => a + b, 0);

    return {
      requested: formatList(requested, totalReq),
      sold: formatList(sold, totalSold)
    };
  }, [data]);


  const handleFilterChange = (key: keyof DashboardFilter, value: any) => {
    setFilters(prev => ({ ...prev, [key]: value }));
  };

  if (loading && data.length === 0) {
    return <div className="flex h-full items-center justify-center text-slate-400 p-12">Carregando Dashboard...</div>;
  }

  return (
    <div className="space-y-6 pb-8">
      {/* Filters Bar */}
      <div className="bg-white p-4 rounded-xl shadow-sm border border-slate-100 flex flex-col md:flex-row gap-4 items-center justify-between">
        <div className="flex items-center gap-2 text-slate-500 font-medium">
          <Filter size={18} />
          <span className="hidden md:inline">Filtros:</span>
        </div>
        
        <div className="flex flex-wrap items-center gap-3 w-full md:w-auto">
          <DateRangePicker 
            dateRange={filters.dateRange} 
            onChange={(range) => handleFilterChange('dateRange', range)} 
          />

          <select 
            className="bg-slate-50 border border-slate-200 px-3 py-2 rounded-lg text-sm text-slate-700 outline-none focus:ring-2 focus:ring-blue-100 cursor-pointer hover:border-slate-300"
            value={filters.userId}
            onChange={(e) => handleFilterChange('userId', e.target.value)}
          >
            <option value="all">Todos Usuários</option>
            {users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
          </select>

           <select 
            className="bg-slate-50 border border-slate-200 px-3 py-2 rounded-lg text-sm text-slate-700 outline-none focus:ring-2 focus:ring-blue-100 cursor-pointer hover:border-slate-300"
            value={filters.teamId}
            onChange={(e) => handleFilterChange('teamId', e.target.value)}
          >
            <option value="all">Todas Equipes</option>
            {teams.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
          </select>
        </div>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <KPICard 
          title="Total de Leads" 
          value={totalLeads} 
          trend="up" 
          trendValue="12%" 
          icon={Users} 
          colorClass="text-blue-600"
        />
        <KPICard 
          title="Nota Média Qualidade" 
          value={avgScore} 
          subValue="/ 100"
          trend={Number(avgScore) > 75 ? 'up' : 'down'}
          trendValue="2.1"
          icon={TrendingUp} 
          colorClass="text-purple-600"
        />
        <KPICard 
          title="Média 1ª Resposta" 
          value={`${avgResponseTime}m`} 
          trend="down"
          trendValue="bom" 
          icon={Clock} 
          colorClass="text-orange-500"
        />
         <KPICard 
          title="Tempo Médio Atend." 
          value={`${avgHandleTime}m`} 
          subValue="por lead"
          icon={Phone} 
          colorClass="text-green-600"
        />
      </div>

      {/* Charts Section */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Funnel Chart */}
        <div className="lg:col-span-2 bg-white p-6 rounded-2xl shadow-sm border border-slate-100 min-h-[400px]">
          <h3 className="text-lg font-bold text-slate-800 mb-6">Funil de Vendas</h3>
          <div className="h-[300px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart
                data={funnelData}
                layout="vertical"
                margin={{ top: 5, right: 30, left: 40, bottom: 5 }}
                barSize={32}
              >
                <CartesianGrid strokeDasharray="3 3" horizontal={true} vertical={false} stroke="#f1f5f9" />
                <XAxis type="number" hide />
                <YAxis 
                  dataKey="name" 
                  type="category" 
                  width={120} 
                  tick={{fill: '#475569', fontSize: 13, fontWeight: 500}} 
                  tickLine={false}
                  axisLine={false}
                />
                <Tooltip 
                  cursor={{fill: '#f8fafc'}}
                  contentStyle={{ borderRadius: '12px', border: 'none', boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)' }}
                />
                <Bar dataKey="value" radius={[0, 6, 6, 0]}>
                  {funnelData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS.charts[index % COLORS.charts.length]} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>

        {/* Origin Pie Chart */}
        <div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 min-h-[400px] flex flex-col">
          <h3 className="text-lg font-bold text-slate-800 mb-2">Origem dos Leads</h3>
          <div className="flex-1 min-h-0">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={originData}
                  cx="50%"
                  cy="50%"
                  innerRadius={70}
                  outerRadius={100}
                  paddingAngle={5}
                  dataKey="value"
                  stroke="none"
                >
                  {originData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS.charts[index % COLORS.charts.length]} />
                  ))}
                </Pie>
                <Tooltip contentStyle={{ borderRadius: '12px' }} />
                <Legend 
                  verticalAlign="bottom" 
                  height={80} 
                  iconType="circle" 
                  iconSize={10}
                  wrapperStyle={{ fontSize: '12px', paddingTop: '20px' }}
                />
              </PieChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>

      {/* Ranking Table */}
      <SellersTable data={sellersRanking} />

      {/* Product Lists */}
      <ProductLists requested={productStats.requested} sold={productStats.sold} />
    </div>
  );
};
