/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState } from 'react';
import { Users, Search, Phone, Mail, ChevronRight, Award, MapPin } from 'lucide-react';
import { useFiestaTenantCustomers, useFiestaTenantLocations } from '../services/fiestaQueries';
import { num as fnum, str as fstr, customerName, customerStoreId } from '../services/fiestaApi';

interface AdminCustomersViewProps {
  tenantId: number;
}

export default function AdminCustomersView({ tenantId }: AdminCustomersViewProps) {
  const [customerSearch, setCustomerSearch] = useState('');

  // Fetch all customers for the tenant by passing locationid: 0
  const customersQ = useFiestaTenantCustomers({
    tenantid: tenantId,
    locationid: 0,
    pagesize: 500,
  });

  const locationsQ = useFiestaTenantLocations(tenantId);
  const locations = locationsQ.data ?? [];

  const getMergedCustomers = () => {
    const rawCustomers = customersQ.data ?? [];
    return rawCustomers.map((c: any) => {
      const id =
        fnum(c.customerid) ||
        fnum(c.customerheaderid) ||
        fnum(c.userid) ||
        fnum(c.id) ||
        null;
      const spent = fnum(c.totalspent);
      
      // `locationid` is not a column on this response — the store link is
      // aliased `tenantlocationid`. Matching on the wrong name meant every
      // customer fell through to the invented store name 'Central'.
      const locId = customerStoreId(c);
      const loc = locations.find((l: any) => fnum(l.locationid) === locId);
      const storeName = (loc ? fstr(loc.locationname) : fstr(c.locationname)).trim() || '—';

      return {
        id,
        name: customerName(c) || 'Customer',
        phone: fstr(c.contactno) || '—',
        email: fstr(c.email),
        address: fstr(c.address) || '—',
        ordersCount: Number(c.orderscount) || 0,
        totalSpent: spent > 0 ? `₹${spent.toLocaleString('en-IN')}` : '—',
        storeName,
      };
    });
  };

  const customersList = getMergedCustomers().filter(c =>
    c.name.toLowerCase().includes(customerSearch.toLowerCase()) ||
    c.phone.includes(customerSearch) ||
    c.address.toLowerCase().includes(customerSearch.toLowerCase()) ||
    c.storeName.toLowerCase().includes(customerSearch.toLowerCase())
  );

  // Helper for jewel-tone avatars
  const toneFor = (str: string) => {
    let hash = 0;
    for (let i = 0; i < str.length; i++) hash = str.charCodeAt(i) + ((hash << 5) - hash);
    const hues = [
      { soft: '#f3e8ff', fg: '#6b21a8' }, // purple
      { soft: '#e0e7ff', fg: '#3730a3' }, // indigo
      { soft: '#fce7f3', fg: '#9d174d' }, // pink
      { soft: '#ffedd5', fg: '#9a3412' }, // orange
      { soft: '#dcfce7', fg: '#166534' }, // green
      { soft: '#cffafe', fg: '#155e75' }, // cyan
    ];
    return hues[Math.abs(hash) % hues.length];
  };

  const initialsOf = (name: string) => {
    const p = name.split(' ').filter(Boolean);
    return ((p[0]?.[0] || '') + (p.length > 1 ? p[p.length - 1][0] : '')).toUpperCase();
  };

  const localityOf = (addr: string) => {
    if (!addr) return '';
    const p = addr.split(',');
    return p.length > 1 ? p[p.length - 2].trim() : p[0].trim();
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col md:flex-row justify-between md:items-end gap-4">
        <div>
          <h2 className="text-2xl font-black text-[#0f172a] flex items-center gap-2">
            <Users size={26} className="text-[#662582]" />
            Customers
          </h2>
        </div>

        <div className="relative w-full md:w-72 shrink-0">
          <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-[#662582]" />
          <input
            type="text"
            placeholder="Search customers, stores..."
            value={customerSearch}
            onChange={(e) => setCustomerSearch(e.target.value)}
            className="w-full pl-9 pr-3 py-2.5 border border-[#662582]/20 rounded-xl text-[13px] text-[#0f172a] placeholder:text-zinc-400 outline-none bg-white focus:border-[#662582] focus:ring-4 focus:ring-[#662582]/10 transition-all shadow-sm"
          />
        </div>
      </div>

      {customersQ.isLoading ? (
        <div className="h-64 flex flex-col items-center justify-center space-y-4">
          <div className="relative w-10 h-10">
            <span className="absolute inset-0 rounded-full border-2 border-purple-100" />
            <span className="absolute inset-0 rounded-full border-2 border-t-purple-600 animate-spin" />
          </div>
          <p className="text-xs font-bold text-zinc-400 uppercase tracking-widest">Loading Customers...</p>
        </div>
      ) : customersList.length === 0 ? (
        <div className="bg-white border border-[#e2e8f0] rounded-3xl py-24 flex flex-col items-center gap-4 text-center px-6 shadow-sm">
          <span className="flex items-center justify-center w-16 h-16 rounded-2xl bg-purple-50 text-purple-700 shadow-sm"><Users size={28} /></span>
          <p className="text-lg font-bold text-[#0f172a]">No customers found</p>
          <p className="text-sm text-zinc-500 max-w-[350px] leading-relaxed">
            {customerSearch ? 'Nothing matches your search criteria. Try a different term.' : 'There are no customers registered in the tenant yet.'}
          </p>
          {customerSearch && (
            <button onClick={() => setCustomerSearch('')} className="mt-2 text-[13px] font-bold text-purple-700 bg-purple-50 hover:bg-purple-100 px-4 py-2 rounded-lg transition-colors cursor-pointer">
              Clear Search
            </button>
          )}
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          {customersList.map((c: any, idx: number) => {
            const tone = toneFor(c.name || `c${idx}`);
            const locality = localityOf(c.address);
            return (
              <div key={c.id ?? idx} className="group bg-white border border-[#e2e8f0] rounded-2xl p-5 hover:shadow-lg hover:border-purple-300 transition-all duration-300 flex flex-col">
                <div className="flex justify-between items-start mb-4">
                  <div className="flex items-center gap-3 min-w-0">
                    <span 
                      className="w-12 h-12 rounded-2xl flex items-center justify-center font-bold text-sm shrink-0 border border-white" 
                      style={{ background: tone.soft, color: tone.fg }}
                    >
                      {initialsOf(c.name)}
                    </span>
                    <div className="min-w-0">
                      <h3 className="font-extrabold text-[#0f172a] text-[15px] truncate" title={c.name}>{c.name}</h3>
                      {locality && (
                        <p className="text-[11px] text-zinc-500 mt-0.5 flex items-center gap-1 font-medium truncate" title={locality}>
                          <MapPin size={10} className="shrink-0 text-zinc-400" /> {locality}
                        </p>
                      )}
                    </div>
                  </div>
                  {c.ordersCount > 5 && (
                    <span className="shrink-0 ml-2 px-2 py-1 bg-amber-50 text-amber-700 text-[9px] font-black uppercase tracking-widest rounded-lg border border-amber-200 flex items-center gap-1">
                      <Award size={10} /> Loyal
                    </span>
                  )}
                </div>

                <div className="grid grid-cols-2 gap-3 mb-4">
                  <div className="bg-slate-50 rounded-xl p-3 border border-slate-100">
                    <span className="text-[9px] font-bold text-slate-400 uppercase tracking-widest block">Orders</span>
                    <span className="font-black text-[16px] text-[#0f172a] mt-0.5 block">{c.ordersCount}</span>
                  </div>
                  <div className="bg-emerald-50/50 rounded-xl p-3 border border-emerald-100/50">
                    <span className="text-[9px] font-bold text-emerald-600/70 uppercase tracking-widest block">Gross Spend</span>
                    <span className="font-black text-[16px] text-emerald-700 mt-0.5 block">{c.totalSpent}</span>
                  </div>
                </div>

                <div className="space-y-2 mb-5 flex-1">
                  <div className="flex items-center gap-2 text-xs text-slate-600 font-medium">
                    <div className="w-6 h-6 rounded-lg bg-slate-100 flex items-center justify-center shrink-0"><Phone size={12} className="text-slate-400" /></div>
                    <span className="tabular-nums">{c.phone}</span>
                  </div>
                  {c.email && c.email !== '—' && (
                    <div className="flex items-center gap-2 text-xs text-slate-600 font-medium">
                      <div className="w-6 h-6 rounded-lg bg-slate-100 flex items-center justify-center shrink-0"><Mail size={12} className="text-slate-400" /></div>
                      <span className="truncate" title={c.email}>{c.email}</span>
                    </div>
                  )}
                </div>

                <div className="pt-4 border-t border-slate-100 flex items-center justify-between gap-3 mt-auto">
                  <span className="text-xs font-bold text-purple-700 bg-purple-50 px-3 py-1.5 rounded-lg truncate w-full text-center">
                    {c.storeName}
                  </span>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
