'use client';

import React, { useEffect, useState } from 'react';
import { apiRequest } from '@/lib/api';
import { useAuth } from '@/context/auth-context';
import {
  Users,
  Search,
  ChevronRight,
  Phone,
  User,
  ShoppingBag,
  DollarSign,
  TrendingUp,
  X,
  CreditCard,
  Download,
} from 'lucide-react';

interface CustomerOrder {
  orderNumber: string;
  totalAmount: number;
  status: string;
  paymentStatus: string;
  createdAt: string;
}

interface Customer {
  id: string;
  name: string;
  whatsappNumber: string;
  createdAt: string;
  totalOrders: number;
  totalSpent: number;
  orders: CustomerOrder[];
}

export default function CustomersPage() {
  const { user } = useAuth();
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [selectedCustomer, setSelectedCustomer] = useState<Customer | null>(null);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');

  useEffect(() => {
    loadCustomers();
  }, [user?.id, user?.subscriptionStatus]);

  async function loadCustomers() {
    if (!user || user.subscriptionStatus === 'UNSUBSCRIBED' || user.subscriptionStatus === 'EXPIRED') {
      setLoading(false);
      return;
    }
    try {
      const data = await apiRequest('api/customers');
      setCustomers(data);
      if (selectedCustomer) {
        const refreshed = data.find((c: Customer) => c.id === selectedCustomer.id);
        if (refreshed) {
          setSelectedCustomer(refreshed);
        }
      }
    } catch (err) {
      console.error('Failed to load customers:', err);
    } finally {
      setLoading(false);
    }
  }

  // Calculate Metrics
  const totalCustomers = customers.length;
  const activeCustomers = customers.filter((c) => c.totalOrders > 0).length;
  const totalRevenue = customers.reduce((sum, c) => sum + c.totalSpent, 0);
  const averageLtv = totalCustomers > 0 ? totalRevenue / totalCustomers : 0;

  // Filter list
  const filteredCustomers = customers.filter((c) => {
    const q = searchQuery.toLowerCase();
    return (
      (c.name || '').toLowerCase().includes(q) ||
      (c.whatsappNumber || '').toLowerCase().includes(q)
    );
  });

  const handleExportReport = () => {
    if (!customers || customers.length === 0) {
      alert('No customers available to export.');
      return;
    }
    
    // Define headers
    const headers = [
      'Customer ID',
      'Name',
      'Phone Number',
      'Created Date',
      'Total Orders',
      'Total Spent'
    ];
    
    // Map data rows safely
    const rows = customers.map(c => {
      const spent = (Number(c.totalSpent) || 0).toFixed(2);
      const rawPhone = c.whatsappNumber || '';
      const cleanPhone = rawPhone ? (rawPhone.trim().startsWith('+') ? rawPhone.trim() : `+${rawPhone.trim()}`) : 'N/A';
      const phoneCell = cleanPhone !== 'N/A' ? `\t${cleanPhone}` : 'N/A';
      const custIdCell = c.id ? `\t${c.id}` : 'N/A';
      const date = c.createdAt ? new Date(c.createdAt).toLocaleDateString() : 'N/A';

      return [
        custIdCell,
        c.name || 'Anonymous',
        phoneCell,
        date,
        c.totalOrders || 0,
        spent
      ];
    });
    
    // Construct CSV content
    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.map(val => `"${String(val ?? '').replace(/"/g, '""')}"`).join(','))
    ].join('\n');
    
    // Download trigger with UTF-8 BOM (\uFEFF) for Excel compatibility
    const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', `customer_report_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <div className="space-y-8 relative font-sans">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold tracking-tight text-white Outfit">
            Customers & Activity
          </h1>
          <p className="text-sm text-gray-400 mt-1">
            Manage profiles, view shopping frequency, and track individual customer lifetime value (LTV)
          </p>
        </div>
        <button
          onClick={handleExportReport}
          className="flex items-center gap-2 px-4 py-2.5 bg-emerald-500 hover:bg-emerald-600 text-white font-semibold rounded-lg text-xs transition-all cursor-pointer shadow-md shadow-emerald-500/10 self-start sm:self-center"
        >
          <Download className="h-4 w-4" />
          <span>Export Report</span>
        </button>
      </div>

      {loading ? (
        <div className="flex h-64 items-center justify-center">
          <div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-emerald-500 border-t-transparent"></div>
        </div>
      ) : (
        <>
          {/* Metrics Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            {/* Total Customers Card */}
            <div className="glass-panel rounded-2xl p-6 flex items-center justify-between">
              <div>
                <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider">
                  Total Contacts
                </p>
                <h3 className="text-3xl font-black text-white mt-2 Outfit">
                  {totalCustomers}
                </h3>
              </div>
              <Users className="h-6 w-6 text-emerald-400" />
            </div>

            {/* Active Shoppers Card */}
            <div className="glass-panel rounded-2xl p-6 flex items-center justify-between">
              <div>
                <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider">
                  Active Customers
                </p>
                <h3 className="text-3xl font-black text-white mt-2 Outfit">
                  {activeCustomers}
                </h3>
              </div>
              <ShoppingBag className="h-6 w-6 text-emerald-400" />
            </div>

            {/* Total Customer Revenue Card */}
            <div className="glass-panel rounded-2xl p-6 flex items-center justify-between">
              <div>
                <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider">
                  Customer Value
                </p>
                <h3 className="text-3xl font-black text-white mt-2 Outfit">
                  ${totalRevenue.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                </h3>
              </div>
              <DollarSign className="h-6 w-6 text-emerald-400" />
            </div>

            {/* Average LTV Card */}
            <div className="glass-panel rounded-2xl p-6 flex items-center justify-between">
              <div>
                <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider">
                  Average LTV
                </p>
                <h3 className="text-3xl font-black text-white mt-2 Outfit">
                  ${averageLtv.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                </h3>
              </div>
              <TrendingUp className="h-6 w-6 text-emerald-400" />
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 items-start">
            {/* Customer List */}
            <div className="lg:col-span-2 space-y-4">
              {/* Search Bar */}
              <div className="glass-panel rounded-2xl p-4 flex items-center gap-3">
                <Search className="h-5 w-5 text-gray-500" />
                <input
                  type="text"
                  placeholder="Search customers by name or WhatsApp number..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="bg-transparent border-none outline-none text-sm text-white w-full placeholder:text-gray-600"
                />
              </div>

              {/* Table */}
              <div className="glass-panel rounded-2xl overflow-hidden">
                <div className="overflow-x-auto scrollbar-thin">
                  {filteredCustomers.length === 0 ? (
                    <div className="p-8 text-center text-gray-500 text-sm">
                      No matching customers found.
                    </div>
                  ) : (
                    <table className="w-full min-w-[700px] text-left text-sm text-gray-400">
                      <thead>
                        <tr className="border-b border-white/5 text-[10px] uppercase tracking-wider font-semibold text-gray-500">
                          <th className="p-4 text-left">Customer Details</th>
                          <th className="p-4 text-left">WhatsApp Contact</th>
                          <th className="p-4 text-center">Orders</th>
                          <th className="p-4 text-right">Total Spent</th>
                          <th className="p-4"></th>
                        </tr>
                      </thead>
                      <tbody>
                        {filteredCustomers.map((customer) => {
                          const isActive = selectedCustomer?.id === customer.id;
                          const initials = customer.name
                            ? customer.name.split(' ').map((n) => n[0]).join('').substring(0, 2).toUpperCase()
                            : 'WA';

                          return (
                            <tr
                              key={customer.id}
                              onClick={() => setSelectedCustomer(customer)}
                              className={`border-b border-white/5 hover:bg-white/2 transition-all cursor-pointer ${
                                isActive ? 'bg-white/3 text-white' : ''
                              }`}
                            >
                              <td className="p-4 flex items-center gap-3">
                                <div className="h-8 w-8 rounded-full bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center text-xs font-bold text-emerald-400">
                                  {initials}
                                </div>
                                <div>
                                  <p className="font-bold text-white text-sm">{customer.name}</p>
                                  <span className="text-[10px] text-gray-500 block mt-0.5">
                                    Added on {new Date(customer.createdAt).toLocaleDateString()}
                                  </span>
                                </div>
                              </td>
                              <td className="p-4 font-mono text-xs text-gray-300">
                                {customer.whatsappNumber}
                              </td>
                              <td className="p-4 text-center font-bold text-white">
                                {customer.totalOrders}
                              </td>
                              <td className="p-4 text-right font-semibold text-emerald-400 font-mono">
                                ${customer.totalSpent.toFixed(2)}
                              </td>
                              <td className="p-4 text-right">
                                <ChevronRight className="h-5 w-5 text-gray-500 inline" />
                              </td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  )}
                </div>
              </div>
            </div>

            {/* Sidebar details */}
            <div className="space-y-6">
              {selectedCustomer ? (
                <div className="glass-panel rounded-2xl p-6 space-y-6 relative overflow-hidden animate-in fade-in slide-in-from-right duration-200">
                  <div className="flex justify-between items-start">
                    <div className="flex items-center gap-3">
                      <div className="h-10 w-10 rounded-full bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center text-sm font-bold text-emerald-400">
                        {selectedCustomer.name
                          ? selectedCustomer.name.split(' ').map((n) => n[0]).join('').substring(0, 2).toUpperCase()
                          : 'WA'}
                      </div>
                      <div>
                        <h3 className="font-extrabold text-white text-base font-sans">
                          {selectedCustomer.name}
                        </h3>
                      </div>
                    </div>
                    <button
                      onClick={() => setSelectedCustomer(null)}
                      className="h-7 w-7 rounded-lg hover:bg-white/5 flex items-center justify-center text-gray-400 hover:text-white transition-colors cursor-pointer"
                    >
                      <X className="h-4 w-4" />
                    </button>
                  </div>

                  {/* Summary Stats */}
                  <div className="grid grid-cols-2 gap-4 bg-white/2 border border-white/5 p-4 rounded-xl text-center">
                    <div>
                      <span className="text-[9px] font-bold text-gray-500 uppercase tracking-wider block">Total Orders</span>
                      <span className="text-lg font-black text-white mt-1 block">{selectedCustomer.totalOrders}</span>
                    </div>
                    <div>
                      <span className="text-[9px] font-bold text-gray-500 uppercase tracking-wider block">Total Spent</span>
                      <span className="text-lg font-black text-emerald-400 mt-1 block">${selectedCustomer.totalSpent.toFixed(2)}</span>
                    </div>
                  </div>

                  {/* Contact Info */}
                  <div className="space-y-3">
                    <h4 className="font-bold text-xs uppercase tracking-wider text-gray-500">Contact Channels</h4>
                    <div className="flex items-center gap-2 text-sm text-gray-300">
                      <Phone className="h-4 w-4 text-emerald-400" />
                      <span className="font-mono text-xs">{selectedCustomer.whatsappNumber}</span>
                    </div>
                  </div>

                  {/* Purchase History */}
                  <div className="space-y-3">
                    <h4 className="font-bold text-xs uppercase tracking-wider text-gray-500">Purchase History</h4>
                    {selectedCustomer.orders.length === 0 ? (
                      <div className="text-center py-4 bg-black/15 border border-white/5 rounded-xl text-xs text-gray-500">
                        No orders recorded.
                      </div>
                    ) : (
                      <div className="space-y-3 max-h-[250px] overflow-y-auto pr-1.5">
                        {selectedCustomer.orders.map((order, idx) => (
                          <div
                            key={idx}
                            className="bg-[#efeae2] p-3 rounded-xl border border-slate-300/50 flex justify-between items-center text-xs shadow-sm"
                          >
                            <div className="space-y-1">
                              <span className="font-bold text-slate-900 block">{order.orderNumber}</span>
                              <span className="text-[10px] text-slate-600 block">
                                {new Date(order.createdAt).toLocaleDateString()}
                              </span>
                            </div>
                            <div className="text-right space-y-1">
                              <span className="font-bold text-slate-900 font-mono block">
                                ${order.totalAmount.toFixed(2)}
                              </span>
                              <span className={`inline-block px-1.5 py-0.5 rounded text-[8px] font-extrabold uppercase ${
                                order.paymentStatus === 'PAID'
                                  ? 'bg-emerald-600/15 text-emerald-700'
                                  : order.paymentStatus === 'FAILED'
                                  ? 'bg-red-600/15 text-red-600'
                                  : 'bg-amber-600/15 text-amber-700'
                              }`}>
                                {order.paymentStatus}
                              </span>
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              ) : (
                <div className="glass-panel rounded-2xl p-6 text-center text-gray-500 text-sm py-12">
                  Click any customer on the list to load their detailed contact profile, shopping statistics, and historical purchases.
                </div>
              )}
            </div>
          </div>
        </>
      )}
    </div>
  );
}
