"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { Calendar, FileText, CreditCard, DollarSign, Filter } from "lucide-react";
import { getSupabaseClient } from "@/lib/supabase";
import { getCompanyContext } from "@/lib/company-context";
import { PageHeader } from "@/components/ui/page-header";
import { Input } from "@/components/ui/input";
import { CustomSelect } from "@/components/ui/custom-select";
import { PixIcon, CashIcon, CreditCardIcon, DebitCardIcon, TransferIcon } from "@/components/icons/payment-icons";
import { Valor } from "@/components/ui/valor";

interface Payment {
  id: string;
  order_id: string;
  order_number: number;
  client_name: string;
  client_company?: string;
  amount: number;
  payment_method: 'pix' | 'cash' | 'credit_card' | 'debit_card' | 'transfer';
  payment_date: string;
  notes?: string;
  user_id: string;
  created_at: string;
}

type ClientJoin = { name: string; company_name: string | null };
type OrderJoin = { id: string; number: number; clients: ClientJoin | ClientJoin[] | null };
type PaymentQueryRow = {
  id: string;
  amount: number;
  payment_method: Payment["payment_method"] | string;
  payment_date: string;
  notes: string | null;
  user_id: string;
  created_at: string;
  orders: OrderJoin | OrderJoin[] | null;
};

function firstOrNull<T>(value: T | T[] | null | undefined): T | null {
  if (!value) return null;
  return Array.isArray(value) ? value[0] ?? null : value;
}

function formatMoney(value: number) {
  return new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(value || 0);
}

/* O dinheiro desta tela passa pelo <Valor>: quem nao tem a permissao de ver
   valores continua abrindo a tela e trabalhando, com os numeros borrados. */
const dinheiro = (v: number) => <Valor>{formatMoney(v)}</Valor>;

function formatDate(dateString: string) {
  return new Intl.DateTimeFormat("pt-BR", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit"
  }).format(new Date(dateString));
}

function paymentMethodLabel(method: string) {
  switch (method) {
    case 'pix': return 'Pix';
    case 'cash': return 'Dinheiro';
    case 'credit_card': return 'Cartão Crédito';
    case 'debit_card': return 'Cartão Débito';
    case 'transfer': return 'Transferência';
    default: return method;
  }
}

function startOfDay(date: Date) {
  const d = new Date(date);
  d.setHours(0, 0, 0, 0);
  return d;
}

function addDays(date: Date, days: number) {
  const d = new Date(date);
  d.setDate(d.getDate() + days);
  return d;
}

function getDateRangeForFilter(filter: string) {
  const now = new Date();

  if (filter === "today") {
    const start = startOfDay(now);
    const end = addDays(start, 1);
    return { start, end };
  }

  if (filter === "week") {
    const today = startOfDay(now);
    const jsDay = today.getDay();
    const diffToMonday = (jsDay + 6) % 7;
    const start = addDays(today, -diffToMonday);
    const end = addDays(start, 7);
    return { start, end };
  }

  if (filter === "month") {
    const start = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0, 0);
    const end = new Date(now.getFullYear(), now.getMonth() + 1, 1, 0, 0, 0, 0);
    return { start, end };
  }

  return null;
}

const methodIcons: Record<string, React.ReactNode> = {
  pix: <PixIcon className="w-8 h-8 text-[#4DB6AC]" />,
  cash: <CashIcon className="w-8 h-8 text-green-600" />,
  credit_card: <CreditCardIcon className="w-8 h-8 text-indigo-600" />,
  debit_card: <DebitCardIcon className="w-8 h-8 text-indigo-400" />,
  transfer: <TransferIcon className="w-8 h-8 text-purple-600" />,
};

export default function PaymentsPage() {
  const [payments, setPayments] = useState<Payment[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [paymentMethodFilter, setPaymentMethodFilter] = useState<string>('all');
  const [dateFilter, setDateFilter] = useState<string>('all');

  useEffect(() => {
    fetchPayments();
  }, []);

  async function fetchPayments() {
    try {
      const supabase = getSupabaseClient();
      const {
        data: { user },
      } = await supabase.auth.getUser();
      if (!user) {
        setPayments([]);
        return;
      }

      const ctx = await getCompanyContext(supabase, user);
      const tenantIds = ctx.tenantIds?.length ? ctx.tenantIds : [user.id];
      
      // Buscar pagamentos com informações do pedido e cliente
      const { data, error } = await supabase
        .from('payments')
        .select(`
          id,
          amount,
          payment_method,
          payment_date,
          notes,
          user_id,
          created_at,
          orders!inner (
            id,
            number,
            clients (name, company_name)
          )
        `)
        .in('user_id', tenantIds)
        .order('payment_date', { ascending: false });

      if (error) {
        console.error('Erro ao buscar pagamentos:', error);
        // Em caso de erro, mostrar array vazio para não quebrar a interface
        setPayments([]);
        return;
      }

      if (!data) {
        setPayments([]);
        return;
      }

      const paymentsData = (data as PaymentQueryRow[]).map((payment) => {
        const order = firstOrNull(payment.orders);
        const client = firstOrNull(order?.clients ?? null);

        return {
          id: payment.id,
          order_id: order?.id || '',
          order_number: order?.number || 0,
          client_name: client?.name || 'Cliente não informado',
          client_company: client?.company_name ?? undefined,
          amount: payment.amount,
          payment_method: payment.payment_method as Payment["payment_method"],
          payment_date: payment.payment_date,
          notes: payment.notes ?? undefined,
          user_id: payment.user_id,
          created_at: payment.created_at
        };
      });

      setPayments(paymentsData);

    } catch (error) {
      console.error('Erro ao buscar pagamentos:', error);
      setPayments([]);
    } finally {
      setLoading(false);
    }
  }

  const filteredPayments = payments.filter(payment => {
    // Filtro de busca
    const matchesSearch = 
      payment.client_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      payment.client_company?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      payment.order_number.toString().includes(searchTerm) ||
      payment.notes?.toLowerCase().includes(searchTerm.toLowerCase());
    
    // Filtro por método de pagamento
    const matchesMethod = 
      paymentMethodFilter === 'all' || 
      payment.payment_method === paymentMethodFilter;
    
    // Filtro por período
    const range = getDateRangeForFilter(dateFilter);
    const matchesDate = (() => {
      if (!range) return true;
      const dt = new Date(payment.payment_date);
      if (Number.isNaN(dt.getTime())) return false;
      return dt >= range.start && dt < range.end;
    })();
    
    return matchesSearch && matchesMethod && matchesDate;
  });

  if (loading) {
    return (
      <div className="space-y-6">
        <PageHeader
          title="Pagamentos"
          subtitle="Histórico completo de todos os pagamentos recebidos"
        />
        
        <div className="ks-surface p-6 rounded-xl">
          <div className="animate-pulse space-y-4">
            <div className="h-8 bg-gray-200 rounded"></div>
            <div className="h-8 bg-gray-200 rounded"></div>
            <div className="h-8 bg-gray-200 rounded"></div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title="Pagamentos"
        subtitle="Histórico completo de todos os pagamentos recebidos"
      />

      {/* Filtros */}
      <div className="ks-surface p-6 rounded-xl">
        <h3 className="text-lg font-semibold text-[var(--ks-color-text-primary)] mb-4">Filtros</h3>
        
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="space-y-2">
            <label className="text-sm font-medium text-[var(--ks-color-text-muted)]">Buscar</label>
            <Input
              placeholder="Cliente, empresa, pedido ou observação..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full"
            />
          </div>
          
          <div className="space-y-2">
            <label className="text-sm font-medium text-[var(--ks-color-text-muted)]">Método de Pagamento</label>
            <CustomSelect
              value={paymentMethodFilter}
              onChange={setPaymentMethodFilter}
              options={[
                { value: 'all', label: 'Todos os métodos' },
                { value: 'pix', label: 'Pix' },
                { value: 'cash', label: 'Dinheiro' },
                { value: 'credit_card', label: 'Cartão Crédito' },
                { value: 'debit_card', label: 'Cartão Débito' },
                { value: 'transfer', label: 'Transferência' }
              ]}
              className="w-full"
            />
          </div>
          
          <div className="space-y-2">
            <label className="text-sm font-medium text-[var(--ks-color-text-muted)]">Período</label>
            <CustomSelect
              value={dateFilter}
              onChange={setDateFilter}
              options={[
                { value: 'all', label: 'Todo período' },
                { value: 'today', label: 'Hoje' },
                { value: 'week', label: 'Esta semana' },
                { value: 'month', label: 'Este mês' }
              ]}
              className="w-full"
            />
          </div>
        </div>
      </div>

      {/* Resumo Estatístico */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="ks-surface p-4 rounded-xl">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-[var(--ks-color-text-muted)]">Total Recebido</p>
              <p className="text-lg font-bold text-[var(--ks-color-text-primary)]">
                {dinheiro(payments.reduce((sum, p) => sum + p.amount, 0))}
              </p>
            </div>
            <DollarSign size={20} className="text-green-600" />
          </div>
        </div>
        
        <div className="ks-surface p-4 rounded-xl">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-[var(--ks-color-text-muted)]">Total de Pagamentos</p>
              <p className="text-lg font-bold text-[var(--ks-color-text-primary)]">
                {payments.length}
              </p>
            </div>
            <FileText size={20} className="text-blue-600" />
          </div>
        </div>
        
        <div className="ks-surface p-4 rounded-xl">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-[var(--ks-color-text-muted)]">Método Mais Usado</p>
              <p className="text-lg font-bold text-[var(--ks-color-text-primary)]">
                {payments.length > 0 ? 
                  paymentMethodLabel(
                    Object.entries(
                      payments.reduce((acc, p) => {
                        acc[p.payment_method] = (acc[p.payment_method] || 0) + 1;
                        return acc;
                      }, {} as Record<string, number>)
                    ).sort((a, b) => b[1] - a[1])[0][0]
                  ) : 'N/A'
                }
              </p>
            </div>
            <CreditCard size={20} className="text-purple-600" />
          </div>
        </div>
        
        <div className="ks-surface p-4 rounded-xl">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-[var(--ks-color-text-muted)]">Filtrados</p>
              <p className="text-lg font-bold text-[var(--ks-color-text-primary)]">
                {filteredPayments.length}
              </p>
            </div>
            <Filter size={20} className="text-orange-600" />
          </div>
        </div>
      </div>

      {/* Tabela de Pagamentos - Desktop */}
      <div className="ks-surface overflow-hidden rounded-xl hidden md:block">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[1024px] lg:min-w-0">
            <thead className="bg-[var(--ks-color-bg-subtle)]">
              <tr>
                <th className="text-left py-4 px-4 lg:px-6 text-sm font-medium text-[var(--ks-color-text-muted)] w-[180px]">
                  Data
                </th>
                <th className="text-left py-4 px-4 lg:px-6 text-sm font-medium text-[var(--ks-color-text-muted)] w-[100px]">
                  Pedido
                </th>
                <th className="text-left py-4 px-4 lg:px-6 text-sm font-medium text-[var(--ks-color-text-muted)] w-[200px]">
                  Cliente
                </th>
                <th className="text-left py-4 px-4 lg:px-6 text-sm font-medium text-[var(--ks-color-text-muted)] w-[140px]">
                  Método
                </th>
                <th className="text-left py-4 px-4 lg:px-6 text-sm font-medium text-[var(--ks-color-text-muted)] w-[120px]">
                  Valor
                </th>
                <th className="text-left py-4 px-4 lg:px-6 text-sm font-medium text-[var(--ks-color-text-muted)] min-w-[150px]">
                  Observações
                </th>
                <th className="text-left py-4 px-4 lg:px-6 text-sm font-medium text-[var(--ks-color-text-muted)] w-[120px]">
                  Ações
                </th>
              </tr>
            </thead>
            
            <tbody className="divide-y divide-[var(--ks-color-border-subtle)]">
              {filteredPayments.map((payment) => (
                <tr key={payment.id} className="hover:bg-[var(--ks-color-bg-subtle)] transition-colors">
                  <td className="py-4 px-4 lg:px-6">
                    <div className="flex items-center gap-2">
                      <div className="w-8 h-8 bg-[var(--ks-color-primary-light)] rounded-lg flex items-center justify-center flex-shrink-0">
                        <Calendar size={14} className="text-[var(--ks-color-primary)]" />
                      </div>
                      <span className="text-sm font-medium text-[var(--ks-color-text-primary)] whitespace-nowrap">
                        {formatDate(payment.payment_date)}
                      </span>
                    </div>
                  </td>
                  
                  <td className="py-4 px-4 lg:px-6">
                    <span className="font-semibold text-[var(--ks-color-text-primary)] bg-[var(--ks-color-primary-light)] px-2 py-1 rounded-md text-xs">
                      #{payment.order_number}
                    </span>
                  </td>
                  
                  <td className="py-4 px-4 lg:px-6">
                    <div className="min-w-0 max-w-[180px]">
                      <p className="text-sm font-medium text-[var(--ks-color-text-primary)] truncate">
                        {payment.client_name}
                      </p>
                      {payment.client_company && (
                        <p className="text-xs text-[var(--ks-color-text-muted)] truncate">
                          {payment.client_company}
                        </p>
                      )}
                    </div>
                  </td>
                  
                  <td className="py-4 px-4 lg:px-6">
                    <div className="flex justify-center">
                      {methodIcons[payment.payment_method] || <div className="w-8 h-8 bg-gray-200 rounded-lg flex items-center justify-center">💰</div>}
                    </div>
                  </td>
                  
                  <td className="py-4 px-4 lg:px-6">
                    <span className="text-sm font-semibold text-green-600 bg-green-50 px-2 py-1 rounded-md">
                      {dinheiro(payment.amount)}
                    </span>
                  </td>
                  
                  <td className="py-4 px-4 lg:px-6">
                    <span className="text-xs text-[var(--ks-color-text-muted)] line-clamp-2 max-w-[150px]">
                      {payment.notes || '—'}
                    </span>
                  </td>
                  
                  <td className="py-4 px-4 lg:px-6">
                    <Link
                      href={`/dashboard/orders/${payment.order_id}`}
                      className="ks-button ks-button-secondary ks-button-sm whitespace-nowrap text-xs"
                    >
                      <FileText size={12} />
                      Ver Pedido
                    </Link>
                  </td>
                </tr>
               ))}
            </tbody>
          </table>

           {filteredPayments.length === 0 && (
            <div className="text-center py-16">
              <div className="w-20 h-20 bg-[var(--ks-color-bg-subtle)] rounded-full flex items-center justify-center mx-auto mb-4">
                <CreditCard size={32} className="text-[var(--ks-color-text-muted)]" />
              </div>
              <p className="text-[var(--ks-color-text-muted)] text-lg font-medium">
                {searchTerm ? 'Nenhum pagamento encontrado' : 'Nenhum pagamento registrado'}
              </p>
              <p className="text-sm text-[var(--ks-color-text-soft)] mt-2">
                {searchTerm ? 'Tente ajustar os filtros de busca' : 'Os pagamentos aparecerão aqui quando forem registrados nos pedidos'}
              </p>
            </div>
          )}
        </div>
      </div>

      {/* Tabela de Pagamentos - Mobile */}
      <div className="ks-surface rounded-xl md:hidden">
        <div className="divide-y divide-[var(--ks-color-border-subtle)]">
          {filteredPayments.length === 0 ? (
            <div className="text-center py-12">
              <div className="w-16 h-16 bg-[var(--ks-color-bg-subtle)] rounded-full flex items-center justify-center mx-auto mb-4">
                <CreditCard size={24} className="text-[var(--ks-color-text-muted)]" />
              </div>
              <p className="text-[var(--ks-color-text-muted)]">
                {searchTerm ? 'Nenhum pagamento encontrado' : 'Nenhum pagamento registrado'}
              </p>
              <p className="text-sm text-[var(--ks-color-text-soft)] mt-2">
                {searchTerm ? 'Tente ajustar os filtros de busca' : 'Os pagamentos aparecerão aqui quando forem registrados nos pedidos'}
              </p>
            </div>
          ) : (
            filteredPayments.map((payment) => (
              <div key={payment.id} className="p-4 hover:bg-[var(--ks-color-bg-subtle)]">
                {/* Cabeçalho do Card */}
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <div className="w-8 h-8 bg-[var(--ks-color-primary-light)] rounded-lg flex items-center justify-center">
                      <Calendar size={14} className="text-[var(--ks-color-primary)]" />
                    </div>
                    <span className="font-medium text-[var(--ks-color-text-primary)]">
                      Pedido #{payment.order_number}
                    </span>
                  </div>
                  <div className="flex items-center gap-2">
                    {methodIcons[payment.payment_method] || <div className="w-6 h-6 bg-gray-200 rounded-lg flex items-center justify-center">💰</div>}
                  </div>
                </div>

                {/* Data */}
                <div className="mb-3">
                  <p className="text-xs text-[var(--ks-color-text-muted)]">Data do Pagamento</p>
                  <p className="text-sm font-medium text-[var(--ks-color-text-primary)]">
                    {formatDate(payment.payment_date)}
                  </p>
                </div>

                {/* Informações do Cliente */}
                <div className="mb-3">
                  <p className="text-xs text-[var(--ks-color-text-muted)]">Cliente</p>
                  <p className="text-sm font-medium text-[var(--ks-color-text-primary)]">
                    {payment.client_name}
                  </p>
                  {payment.client_company && (
                    <p className="text-xs text-[var(--ks-color-text-muted)]">
                      {payment.client_company}
                    </p>
                  )}
                </div>

                {/* Valor */}
                <div className="mb-3">
                  <p className="text-xs text-[var(--ks-color-text-muted)]">Valor</p>
                  <p className="text-lg font-semibold text-green-600">
                    {dinheiro(payment.amount)}
                  </p>
                </div>

                {/* Observações */}
                {payment.notes && (
                  <div className="mb-3">
                    <p className="text-xs text-[var(--ks-color-text-muted)]">Observações</p>
                    <p className="text-sm text-[var(--ks-color-text-primary)]">
                      {payment.notes}
                    </p>
                  </div>
                )}

                {/* Ação */}
                <div className="flex justify-end">
                  <Link
                    href={`/dashboard/orders/${payment.order_id}`}
                    className="ks-button ks-button-secondary ks-button-sm w-full sm:w-auto"
                  >
                    <FileText size={14} />
                    Ver Pedido
                  </Link>
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
}
