import React, { useState } from 'react';
import { 
  Users, Trash2, Search, Filter, Phone, ShoppingBag, Truck, Calendar, MapPin, Download, Edit3, ShoppingCart
} from 'lucide-react';
import { Lead, Order } from '../../types';

interface LeadsManagerProps {
  leads: Lead[];
  updateLeads: (leads: Lead[]) => void;
  orders: Order[];
  updateOrders: (orders: Order[]) => void;
  canAccess: (section: string, action?: 'view' | 'edit' | 'delete') => boolean;
  showToast: (msg: string, type: 'success' | 'error') => void;
  deleteItem: (table: string, id: string) => void;
  getTenantHeaders: (extra?: Record<string, string>) => Record<string, string>;
  setActiveTab: (tab: any) => void;
}

const downloadCSV = (data: any[], filename: string, headers: string[]) => {
  const csvRows = [];
  csvRows.push(headers.join(','));
  for (const row of data) {
    const values = [
      row.name || row.customer_name || 'N/A',
      row.phone,
      row.address ? `"${row.address.replace(/"/g, '""')}"` : 'N/A',
      row.product ? `"${row.product.replace(/"/g, '""')}"` : 'N/A',
      row.status,
      new Date(row.created_at).toLocaleString()
    ];
    csvRows.push(values.join(','));
  }
  const blob = new Blob([csvRows.join('\n')], { type: 'text/csv' });
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.setAttribute('href', url);
  a.setAttribute('download', filename);
  a.click();
};

export default function LeadsManager({
  leads, updateLeads, orders, updateOrders, canAccess, showToast, deleteItem, getTenantHeaders, setActiveTab
}: LeadsManagerProps) {
  const [leadStatusFilter, setLeadStatusFilter] = useState('all');
  const [leadSearch, setLeadSearch] = useState('');

  const validLeads = leads.filter((lead: Lead) => {
    const phone = lead.phone?.replace(/\D/g, '');
    return phone && phone.length === 11;
  });

  const uniqueLeads = Array.from(
    new Map(validLeads.map(lead => [lead.phone, lead])).values()
  );

  const filteredLeads = uniqueLeads.filter((lead: Lead) => {
    const inStatus = leadStatusFilter === 'all' ? true : lead.status === leadStatusFilter;
    const inSearch = leadSearch === '' ? true :
      (lead.phone && lead.phone.includes(leadSearch)) ||
      ((lead.name || lead.customer_name || '') && (lead.name || lead.customer_name || '').toLowerCase().includes(leadSearch.toLowerCase()));
    return inStatus && inSearch;
  });

  const sortedLeads = [...filteredLeads].sort((a, b) => new Date(b.created_at || 0).getTime() - new Date(a.created_at || 0).getTime());
  const updateLeadStatus = async (phone: string, newStatus: string) => {
    if (!canAccess('leads', 'edit')) {
      showToast('You do not have permission to update leads', 'error');
      return;
    }

    try {
      if (newStatus === 'converted') {
        // ─── Server-side atomic conversion ───────────────────────────────
        // Reads lead from DB, creates order with full data, deletes lead
        const lead = leads.find((l: Lead) => l.phone === phone);
        const response = await fetch('/api/admin/orders', {
          method: 'POST',
          headers: getTenantHeaders({ 'Accept': 'application/json' }),
          body: JSON.stringify({
            customer_name: lead?.name || lead?.customer_name || 'Unknown Lead',
            customer_phone: phone,
            customer_address: lead?.address || 'N/A',
            items: [{
              product_id: 'L-1',
              name: lead?.product || lead?.product_context || 'Custom Order',
              qty: 1,
              price: 0
            }],
            total: 0,
            payment_method: 'cod'
          })
        });

        const data = await response.json();
        if (!data.success) throw new Error(data.error || 'Conversion failed');

        // Add the returned order to local state (deduped)
        const newOrder: Order = {
          id: data.data.id || data.order?.id,
          customerName: data.data.customer_name || data.order?.customerName,
          phone: data.data.customer_phone || data.order?.phone,
          address: data.data.customer_address || data.order?.address,
          items: data.data.items ?? [],
          subtotal: data.data.subtotal ?? 0,
          deliveryCharge: data.data.delivery_charge ?? 0,
          total: data.data.total ?? 0,
          status: 'pending' as any,
          source: 'Lead Conversion',
          date: data.data.created_at || new Date().toISOString()
        };
        updateOrders([newOrder, ...orders.filter(o => o.id !== newOrder.id)]);

        // Remove lead from local state
        updateLeads(leads.filter((l: Lead) => l.phone !== phone));

        showToast('✅ Lead converted to Order and removed from Incomplete Orders!', 'success');
        setActiveTab('orders');

      } else {
        // Just update status in DB + local state
        const response = await fetch('/api/admin/leads', {
          method: 'POST',
          headers: getTenantHeaders({ 'Content-Type': 'application/json' }),
          body: JSON.stringify({ phone, status: newStatus })
        });
        if (!response.ok) throw new Error('Failed to update lead status');
        const data = await response.json();
        if (!data.success) throw new Error(data.error || 'Unknown error');

        updateLeads(leads.map((l: Lead) =>
          l.phone === phone ? { ...l, status: newStatus } : l
        ));
        showToast(`Lead status updated to ${newStatus}`, 'success');
      }
    } catch (err: any) {
      showToast('Error: ' + err.message, 'error');
    }
  };



  const sendToSteadFast = async (orderId: string) => {
    try {
      const response = await fetch(`${''}/courier.php?action=send-single`, {
        method: 'POST',
        headers: getTenantHeaders({ 'Accept': 'application/json' }),
        body: JSON.stringify({ order_id: orderId })
      });

      const data = await response.json();

      if (data.success) {
        showToast(`Order ${orderId} sent to SteadFast`, 'success');
        const ordersResponse = await fetch('/api/admin/orders', { headers: getTenantHeaders() });
        const ordersData = await ordersResponse.json();
        if (ordersData.success && ordersData.data) {
          const mappedOrders = ordersData.data.map((order: any) => ({
            id: order.id,
            session_id: order.session_id,
            customerName: order.customer_name || 'Anonymous',
            phone: order.phone || '',
            address: order.address || '',
            items: order.items || [],
            subtotal: order.subtotal || 0,
            deliveryCharge: order.delivery_charge || 0,
            total: order.total || 0,
            status: order.status || 'pending',
            source: order.source || 'Website',
            date: order.created_at || new Date().toISOString(),
            confirmed_at: order.confirmed_at,
            courier_status: order.courier_status,
            courier_consignment_id: order.courier_consignment_id,
            courier_invoice: order.courier_invoice,
            label_generated: order.label_generated || 0
          }));
          updateOrders(mappedOrders);
        }
      } else {
        showToast(data.error || 'Failed to send', 'error');
      }
    } catch (error) {
      showToast('Network error', 'error');
    }
  };

  const printLabel = (orderId: string) => {
    window.open(`${''}/courier.php?action=label&order_id=${orderId}`, '_blank');
  };

  const scrollToSection = (id: string) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: 'smooth' });
  };


  return (
    <>

                <div className="space-y-6">
                  <div className="flex justify-between items-center">
                    <h2 className="text-3xl font-black text-black">Incomplete Orders Management </h2>
                    <div className="flex items-center gap-4">
                      <input
                        type="text"
                        placeholder="Search phone/name..."
                        value={leadSearch}
                        onChange={(e) => setLeadSearch(e.target.value)}
                        className="bg-white dark:bg-slate-800 px-4 py-2 rounded-2xl border text-sm w-64 text-black font-bold"
                      />
                      <select
                        value={leadStatusFilter}
                        onChange={(e) => setLeadStatusFilter(e.target.value)}
                        className="bg-white dark:bg-slate-800 px-4 py-2 rounded-2xl border text-sm text-black font-bold"
                      >
                        <option value="all">All Status</option>
                        <option value="partial_entry">Partial</option>
                        <option value="Lead">Lead</option>
                        <option value="Lead - In Progress">In Progress</option>
                        <option value="converted">Converted</option>
                        <option value="Abandoned Lead">Abandoned</option>
                      </select>
                      <button
                        onClick={() => {
                          const headers = ['Phone', 'Name', 'Address', 'Product Context', 'Status', 'Last Updated'];
                          downloadCSV(sortedLeads, `leads_${new Date().toISOString().split('T')[0]}.csv`, headers);
                        }}
                        className="flex items-center gap-2 bg-green-600 text-white px-4 py-2 rounded-2xl text-sm hover:bg-green-700"
                      >
                        <Download size={16} /> CSV
                      </button>
                    </div>
                  </div>

                  <div className="bg-white dark:bg-slate-900 rounded-[32px] shadow-sm border overflow-hidden">
                    <table className="w-full">
                      <thead className="bg-slate-50 text-xs font-black uppercase text-slate-500 dark:text-slate-400">
                        <tr>
                          <th className="px-4 py-4 text-left">#</th>
                          <th className="px-4 py-4 text-left">Phone</th>
                          <th className="px-4 py-4 text-left">Name</th>
                          <th className="px-4 py-4 text-left">Address</th>
                          <th className="px-4 py-4 text-left">Product</th>
                          <th className="px-4 py-4 text-left">Status</th>
                          <th className="px-4 py-4 text-left">Last Updated</th>
                          <th className="px-4 py-4 text-left">Action</th>
                        </tr>
                      </thead>
                      <tbody>
                        {sortedLeads.length > 0 ? sortedLeads.map((lead: Lead, index) => (
                          <tr key={lead.phone} className="border-t hover:bg-slate-50">
                            <td className="px-4 py-4 font-mono text-sm text-slate-500 dark:text-slate-400">{index + 1}</td>
                            <td className="px-4 py-4 font-mono">
                              <div className="flex items-center gap-1.5">
                                <a href={`tel:${lead.phone}`} className="bg-red-50 flex items-center justify-center hover:bg-red-100 w-6 h-6 rounded-full text-red-600 transition-colors cursor-pointer" title="Call Lead">
                                  <Phone size={12} />
                                </a>
                                <span className="text-red-600 font-bold">{lead.phone}</span>
                              </div>
                            </td>
                            <td className="px-4 py-4 text-black font-black">{lead.name || lead.customer_name || (lead as any).customerName || '-'}</td>
                            <td className="px-4 py-4 max-w-[150px] truncate text-black font-bold">{lead.address || '-'}</td>
                            <td className="px-4 py-4 max-w-[150px] truncate text-black font-bold">{lead.product || lead.product_context || (lead as any).productContext || '-'}</td>
                            <td className="px-4 py-4">
                              <select
                                value={lead.status || 'Lead'}
                                onChange={(e) => updateLeadStatus(lead.phone, e.target.value)}
                                disabled={!canAccess('leads', 'edit')}
                                className={`px-2 py-1 rounded-full text-[10px] font-black border-none ${lead.status === 'partial_entry' ? 'bg-black text-white' :
                                  lead.status === 'Lead' ? 'bg-blue-100 text-blue-700' :
                                    lead.status === 'Lead - In Progress' ? 'bg-amber-100 text-amber-700' :
                                      lead.status === 'converted' ? 'bg-green-100 text-green-700' :
                                        lead.status === 'Abandoned Lead' ? 'bg-red-100 text-red-700' :
                                          'bg-gray-100 text-gray-700'
                                  } ${!canAccess('leads', 'edit') && 'opacity-50 cursor-not-allowed'}`}
                              >
                                <option value="partial_entry">Partial</option>
                                <option value="Lead">Lead</option>
                                <option value="Lead - In Progress">In Progress</option>
                                <option value="converted">Converted</option>
                                <option value="Abandoned Lead">Abandoned</option>
                              </select>
                            </td>
                            <td className="px-4 py-4 text-sm text-black font-bold">{lead.updated_at ? new Date(lead.updated_at).toLocaleDateString() : '-'}</td>
                            <td className="px-4 py-4">
                              <div className="flex items-center gap-1">
                                {canAccess('orders', 'edit') && lead.status !== 'converted' && (
                                  <button
                                    onClick={() => updateLeadStatus(lead.phone, 'converted')}
                                    title="Convert to Order"
                                    className="flex items-center gap-1.5 text-green-600 hover:text-white bg-green-50 hover:bg-green-600 px-3 py-1.5 rounded-xl text-[10px] font-black transition-all"
                                  >
                                    <ShoppingCart size={12} /> Convert
                                  </button>
                                )}
                                {canAccess('leads', 'delete') && (
                                  <button
                                    onClick={() => deleteItem('leads', lead.phone)}
                                    className="text-red-500 hover:text-red-700 p-2 hover:bg-red-50 rounded-xl transition-all"
                                  >
                                    <Trash2 size={16} />
                                  </button>
                                )}
                              </div>
                            </td>
                          </tr>
                        )) : (
                          <tr>
                            <td colSpan={8} className="px-4 py-12 text-center text-slate-500 dark:text-slate-400">
                              No incomplete orders found
                            </td>
                          </tr>
                        )}
                      </tbody>
                    </table>
                  </div>
                </div>


    </>
  );
}
