import { useEffect, useState } from 'react';
import { useParams, Link, useOutletContext } from 'react-router-dom';
import { ArrowLeft, User, Tag, Package, DollarSign, Clock, Phone, ChevronLeft, ChevronRight, ShoppingBag, ReceiptText } from 'lucide-react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import DateRangePicker from '../components/DateRangePicker';
import type { ClientDetailsAnalytics, DateRange } from '../types';
import { fetchClientDetailsAnalytics } from '../dataService';

type CustomTooltipProps = {
  active?: boolean;
  payload?: Array<{ value: number }>;
  label?: string;
};

const CustomTooltip = ({ active, payload, label }: CustomTooltipProps) => {
  if (active && payload && payload.length) {
    return (
      <div className="rounded-xl bg-dark-card p-3 shadow-lg">
        <p className="mb-1 font-bold text-brand-primary">{label}</p>
        <p className="m-0 text-dark-text">
          Gasto: {new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(payload[0].value)}
        </p>
      </div>
    );
  }
  return null;
};

const ClientDetails = () => {
  const { clientToken } = useParams<{ clientToken: string }>();
  const decodedClientToken = clientToken ? decodeURIComponent(clientToken) : '';
  const { dateRange, setDateRange } = useOutletContext<{
    dateRange: DateRange,
    setDateRange: (range: DateRange) => void
  }>();
  const [details, setDetails] = useState<ClientDetailsAnalytics | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [ordersPerPage, setOrdersPerPage] = useState(5);

  useEffect(() => {
    let isMounted = true;

    const loadClientDetails = async () => {
      if (!decodedClientToken) {
        if (isMounted) {
          setDetails(null);
          setIsLoading(false);
        }
        return;
      }

      setIsLoading(true);
      const nextDetails = await fetchClientDetailsAnalytics(decodedClientToken, dateRange);

      if (isMounted) {
        setDetails(nextDetails);
        setIsLoading(false);
      }
    };

    void loadClientDetails();

    return () => {
      isMounted = false;
    };
  }, [dateRange, decodedClientToken]);

  const formatCurrency = (value: number) => {
    return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(value);
  };

  const formatNumber = (value: number) => {
    return new Intl.NumberFormat('pt-BR').format(value);
  };

  const handleDateRangeChange = (range: DateRange) => {
    setCurrentPage(1);
    setDateRange(range);
  };

  if (isLoading) {
    return (
      <div className="text-center py-12">
        <p className="text-zinc-500 dark:text-dark-muted font-medium">Carregando cliente...</p>
      </div>
    );
  }

  if (!details?.hasClient) {
    return (
      <div className="text-center py-12">
        <p className="text-zinc-500 dark:text-dark-muted font-medium">Cliente não encontrado.</p>
        <Link to="/clients" className="text-brand-primary hover:underline mt-4 inline-block font-bold">Voltar para clientes</Link>
      </div>
    );
  }

  const {
    chartData,
    groupedOrders,
    allTimeOrderCount,
    clientName,
    clientPhone,
    periodAverageTicket,
    periodItems,
    periodOrderCount,
    periodSpent
  } = details;
  const displayName = clientName || 'Cliente';
  const totalPages = Math.ceil(groupedOrders.length / ordersPerPage);
  const safeCurrentPage = Math.min(currentPage, totalPages || 1);
  const startIndex = (safeCurrentPage - 1) * ordersPerPage;
  const paginatedOrders = groupedOrders.slice(startIndex, startIndex + ordersPerPage);

  return (
    <div className="space-y-6">
      {/* Header Area */}
      <div className="flex flex-col gap-4">
        <Link to="/clients" className="inline-flex items-center text-sm font-bold text-zinc-400 dark:text-dark-muted hover:text-zinc-900 dark:hover:text-dark-text transition-colors w-fit">
          <ArrowLeft className="w-4 h-4 mr-2" />
          Voltar
        </Link>
        
        <div className="flex flex-col md:flex-row md:items-end justify-between gap-6">
          <div className="flex items-center gap-4">
            <div className="w-16 h-16 rounded-2xl bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border flex items-center justify-center shadow-sm">
              <User className="w-8 h-8 text-brand-primary" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-zinc-900 dark:text-dark-text">{displayName}</h1>
              <div className="flex items-center gap-3 mt-1">
                <p className="text-zinc-500 dark:text-dark-muted font-medium">
                  {formatNumber(allTimeOrderCount)} pedidos no histórico completo
                </p>
                {clientPhone && (
                  <>
                    <span className="text-zinc-300 dark:text-dark-border">•</span>
                    <span className="flex items-center gap-1.5 text-brand-primary font-bold text-sm bg-brand-primary/10 px-2 py-1 rounded-md">
                      <Phone className="w-3.5 h-3.5" />
                      {clientPhone}
                    </span>
                  </>
                )}
              </div>
            </div>
          </div>
          
          <DateRangePicker
            dateRange={dateRange}
            onChange={handleDateRangeChange}
          />
        </div>
      </div>

      <div className="grid grid-cols-1 gap-4 md:grid-cols-4">
        <div className="bg-dark-card p-5 rounded-2xl border border-dark-border flex items-center justify-between shadow-sm">
          <div>
            <p className="text-xs font-bold text-dark-muted uppercase tracking-widest mb-1">Gasto no Período</p>
            <p className="text-2xl font-bold text-brand-primary">{formatCurrency(periodSpent)}</p>
          </div>
          <div className="p-3 bg-brand-primary/10 rounded-xl text-brand-primary">
            <DollarSign size={22} />
          </div>
        </div>
        <div className="bg-dark-card p-5 rounded-2xl border border-dark-border flex items-center justify-between shadow-sm">
          <div>
            <p className="text-xs font-bold text-dark-muted uppercase tracking-widest mb-1">Ticket no Período</p>
            <p className="text-2xl font-bold text-dark-text">{formatCurrency(periodAverageTicket)}</p>
          </div>
          <div className="p-3 bg-emerald-500/10 rounded-xl text-emerald-400">
            <ReceiptText size={22} />
          </div>
        </div>
        <div className="bg-dark-card p-5 rounded-2xl border border-dark-border flex items-center justify-between shadow-sm">
          <div>
            <p className="text-xs font-bold text-dark-muted uppercase tracking-widest mb-1">Total Pedidos</p>
            <p className="text-2xl font-bold text-dark-text">{formatNumber(periodOrderCount)}</p>
          </div>
          <div className="p-3 bg-blue-500/10 rounded-xl text-blue-300">
            <ShoppingBag size={22} />
          </div>
        </div>
        <div className="bg-dark-card p-5 rounded-2xl border border-dark-border flex items-center justify-between shadow-sm">
          <div>
            <p className="text-xs font-bold text-dark-muted uppercase tracking-widest mb-1">Itens no Período</p>
            <p className="text-2xl font-bold text-dark-text">{formatNumber(periodItems)}</p>
          </div>
          <div className="p-3 bg-purple-500/10 rounded-xl text-purple-300">
            <Package size={22} />
          </div>
        </div>
      </div>

      <div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl p-6 shadow-sm">
        <h3 className="text-lg font-bold mb-8 text-zinc-900 dark:text-dark-text">Gasto por Data</h3>
        {chartData.length === 0 ? (
          <div className="flex h-[320px] items-center justify-center text-sm font-semibold text-zinc-500 dark:text-dark-muted">
            Nenhum gasto no período selecionado.
          </div>
        ) : (
          <div className="h-[320px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={chartData} margin={{ top: 5, right: 30, left: 20, bottom: 80 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#222222" vertical={false} />
                <XAxis
                  dataKey="date"
                  stroke="#888888"
                  fontSize={10}
                  tickLine={false}
                  axisLine={false}
                  interval={0}
                  angle={-45}
                  textAnchor="end"
                  height={80}
                />
                <YAxis stroke="#888888" fontSize={12} tickLine={false} axisLine={false} tickFormatter={(value) => formatCurrency(Number(value))} />
                <Tooltip content={<CustomTooltip />} cursor={{ fill: '#222222' }} />
                <Bar dataKey="value" fill="#9ECAE1" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        )}
      </div>
{/* Orders List */}
<div className="flex flex-col gap-6">
  {paginatedOrders.length === 0 ? (
    <div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl p-8 text-center shadow-sm">
      <p className="text-sm font-bold text-zinc-900 dark:text-dark-text">Nenhum pedido no período selecionado.</p>
      <p className="mt-1 text-sm text-zinc-500 dark:text-dark-muted">Altere o filtro de data para ver outros pedidos deste cliente.</p>
    </div>
  ) : paginatedOrders.map((group, groupIndex) => (
    <div key={groupIndex} className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl overflow-hidden shadow-sm">
      <div className="p-4 border-b border-zinc-100 dark:border-dark-border bg-zinc-50/50 dark:bg-dark-header flex justify-between items-center">
        <h2 className="text-sm font-bold uppercase tracking-wider text-zinc-500 dark:text-dark-muted flex items-center gap-2">
          <Tag className="w-4 h-4 text-brand-primary" />
          Pedido ID: {group.orderId}
        </h2>
        <span className="text-sm font-bold text-brand-primary">
                Total do Pedido: {formatCurrency(group.orderTotal)}
              </span>
            </div>
            
            <div className="divide-y divide-zinc-100 dark:divide-dark-border">
              {group.items.map((order, index) => (
                <div key={`${order.ID_Produto}-${index}`} className="px-4 py-2 flex flex-col md:flex-row md:items-center justify-between gap-3 hover:bg-zinc-50/50 dark:hover:bg-dark-input/30 transition-colors">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-0.5">
                      <div className="flex items-center gap-1">
                        <Tag className="w-3 h-3 text-zinc-400 dark:text-dark-muted" />
                        <span className="text-[10px] font-bold text-zinc-400 dark:text-dark-muted">ID: {order.ID_Produto}</span>
                      </div>
                      {order.Data_Pedido && (
                        <div className="flex items-center gap-1 ml-2">
                          <Clock className="w-3 h-3 text-zinc-400 dark:text-dark-muted" />
                          <span className="text-[10px] font-bold text-zinc-400 dark:text-dark-muted">
                            Comprado: {order.Data_Pedido}
                          </span>
                        </div>
                      )}
                    </div>
                    <h3 className="text-sm font-bold text-zinc-900 dark:text-dark-text truncate mb-1">{order.Descricao_Produto}</h3>
                    
                    <div className="flex gap-4">
                      <div className="flex items-center gap-1.5 text-[11px]">
                        <Package className="w-3.5 h-3.5 text-zinc-400 dark:text-dark-muted" />
                        <span className="text-zinc-500 dark:text-dark-muted font-medium">Qtd: <span className="text-zinc-900 dark:text-dark-text font-bold">{order.Quantidade}</span></span>
                      </div>
                      <div className="flex items-center gap-1.5 text-[11px]">
                        <DollarSign className="w-3.5 h-3.5 text-zinc-400 dark:text-dark-muted" />
                        <span className="text-zinc-500 dark:text-dark-muted font-medium">Preço: <span className="text-zinc-900 dark:text-dark-text font-bold">{formatCurrency(order.Valor_Unitario)}</span></span>
                      </div>
                    </div>
                  </div>
                  
                  <div className="text-right shrink-0">
                    <p className="text-[10px] font-bold text-zinc-400 dark:text-dark-muted uppercase tracking-widest mb-0.5">Subtotal</p>
                    <p className="text-base font-bold text-zinc-900 dark:text-dark-text">{formatCurrency(order.Quantidade * order.Valor_Unitario)}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      <div className="px-6 py-4 border border-zinc-200 dark:border-dark-border rounded-2xl bg-white dark:bg-dark-card flex flex-col sm:flex-row items-center justify-between gap-4">
        <div className="flex items-center gap-2 text-sm text-zinc-500 dark:text-dark-muted">
          <span>Mostrar</span>
          <select
            value={ordersPerPage}
            onChange={(event) => {
              setOrdersPerPage(Number(event.target.value));
              setCurrentPage(1);
            }}
            className="bg-dark-card border border-dark-border rounded-lg px-2 py-1 focus:outline-none focus:border-brand-primary cursor-pointer text-dark-text"
          >
            <option value={5}>5</option>
            <option value={10}>10</option>
            <option value={20}>20</option>
            <option value={50}>50</option>
          </select>
          <span>pedidos por página</span>
        </div>

        <div className="flex items-center gap-4 text-sm">
          <span className="text-zinc-500 dark:text-dark-muted">
            Mostrando {groupedOrders.length > 0 ? startIndex + 1 : 0} a {Math.min(startIndex + ordersPerPage, groupedOrders.length)} de {groupedOrders.length} pedidos
          </span>
          <div className="flex gap-1">
            <button
              onClick={() => setCurrentPage(page => Math.max(1, page - 1))}
              disabled={safeCurrentPage === 1}
              className="p-1 rounded-lg border border-dark-border disabled:opacity-50 disabled:cursor-not-allowed hover:border-brand-primary transition-colors text-dark-muted hover:text-dark-text cursor-pointer bg-dark-card"
            >
              <ChevronLeft className="w-5 h-5" />
            </button>
            <button
              onClick={() => setCurrentPage(page => Math.min(totalPages, page + 1))}
              disabled={safeCurrentPage === totalPages || totalPages === 0}
              className="p-1 rounded-lg border border-dark-border disabled:opacity-50 disabled:cursor-not-allowed hover:border-brand-primary transition-colors text-dark-muted hover:text-dark-text cursor-pointer bg-dark-card"
            >
              <ChevronRight className="w-5 h-5" />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ClientDetails;
