'use client';

import React, { useState } from 'react';
import AppLayout from '@/components/AppLayout';
import { Plus, Search, Users, TrendingUp, ShoppingBag, Star, Edit2, Trash2, Eye, Phone, Mail } from 'lucide-react';
import Icon from '@/components/ui/AppIcon';


interface Customer {
  id: string;
  name: string;
  phone: string;
  email: string;
  location: string;
  totalPurchases: number;
  totalSpent: number;
  lastVisit: string;
  loyaltyPoints: number;
  status: 'active' | 'inactive' | 'vip';
}

const customers: Customer[] = [
  { id: 'C001', name: 'Grace Wanjiku', phone: '+254 712 345 678', email: 'grace.w@gmail.com', location: 'Westlands, Nairobi', totalPurchases: 48, totalSpent: 125400, lastVisit: '2026-08-07', loyaltyPoints: 1254, status: 'vip' },
  { id: 'C002', name: 'James Otieno', phone: '+254 722 456 789', email: 'j.otieno@yahoo.com', location: 'Kilimani, Nairobi', totalPurchases: 22, totalSpent: 54200, lastVisit: '2026-08-05', loyaltyPoints: 542, status: 'active' },
  { id: 'C003', name: 'Fatuma Hassan', phone: '+254 733 567 890', email: 'fatuma.h@gmail.com', location: 'Parklands, Nairobi', totalPurchases: 35, totalSpent: 89750, lastVisit: '2026-08-06', loyaltyPoints: 897, status: 'vip' },
  { id: 'C004', name: 'Peter Kamau', phone: '+254 700 678 901', email: 'pkamau@outlook.com', location: 'Ruaka, Kiambu', totalPurchases: 8, totalSpent: 18300, lastVisit: '2026-07-28', loyaltyPoints: 183, status: 'active' },
  { id: 'C005', name: 'Aisha Mwangi', phone: '+254 711 789 012', email: 'aisha.m@gmail.com', location: 'Lavington, Nairobi', totalPurchases: 15, totalSpent: 42600, lastVisit: '2026-08-01', loyaltyPoints: 426, status: 'active' },
  { id: 'C006', name: 'David Njoroge', phone: '+254 720 890 123', email: 'dnjoroge@gmail.com', location: 'Thika Road, Nairobi', totalPurchases: 3, totalSpent: 6800, lastVisit: '2026-06-15', loyaltyPoints: 68, status: 'inactive' },
  { id: 'C007', name: 'Mary Chebet', phone: '+254 731 901 234', email: 'mary.c@gmail.com', location: 'Eldoret, Uasin Gishu', totalPurchases: 29, totalSpent: 71200, lastVisit: '2026-08-04', loyaltyPoints: 712, status: 'vip' },
];

const statusConfig = {
  active: { label: 'Active', className: 'badge-success' },
  inactive: { label: 'Inactive', className: 'badge-neutral' },
  vip: { label: 'VIP', className: 'badge-warning' },
};

export default function CustomersPage() {
  const [search, setSearch] = useState('');
  const [showModal, setShowModal] = useState(false);

  const filtered = customers.filter((c) =>
    c.name.toLowerCase().includes(search.toLowerCase()) ||
    c.phone.includes(search) ||
    c.email.toLowerCase().includes(search.toLowerCase())
  );

  const totalCustomers = customers.length;
  const vipCount = customers.filter((c) => c.status === 'vip').length;
  const totalRevenue = customers.reduce((sum, c) => sum + c.totalSpent, 0);
  const avgSpend = Math.round(totalRevenue / totalCustomers);

  return (
    <AppLayout>
      <div className="p-6 xl:p-8 max-w-screen-2xl mx-auto space-y-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <h1 className="text-xl font-700 text-foreground">Customers</h1>
            <p className="text-sm text-muted-foreground mt-0.5">Manage customer profiles, loyalty points and purchase history</p>
          </div>
          <button onClick={() => setShowModal(true)} className="btn-primary flex items-center gap-2 px-4 py-2 rounded-md text-sm font-600 text-white">
            <Plus size={16} />
            Add Customer
          </button>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {[
            { label: 'Total Customers', value: totalCustomers, icon: Users, color: 'text-primary', bg: 'bg-primary/10' },
            { label: 'VIP Customers', value: vipCount, icon: Star, color: 'text-warning', bg: 'bg-warning-bg' },
            { label: 'Total Revenue (KES)', value: `${(totalRevenue / 1000).toFixed(0)}K`, icon: TrendingUp, color: 'text-success', bg: 'bg-success-bg' },
            { label: 'Avg. Spend (KES)', value: avgSpend.toLocaleString(), icon: ShoppingBag, color: 'text-info', bg: 'bg-info-bg' },
          ].map((stat) => {
            const Icon = stat.icon;
            return (
              <div key={stat.label} className="card-elevated rounded-xl p-4 flex items-center gap-3">
                <div className={`w-10 h-10 rounded-lg ${stat.bg} flex items-center justify-center flex-shrink-0`}>
                  <Icon size={18} className={stat.color} />
                </div>
                <div>
                  <p className="text-2xl font-700 text-foreground">{stat.value}</p>
                  <p className="text-xs text-muted-foreground">{stat.label}</p>
                </div>
              </div>
            );
          })}
        </div>

        {/* Search */}
        <div className="card-elevated rounded-xl p-4">
          <div className="flex items-center gap-2 bg-muted border border-border rounded-md px-3 h-9 max-w-sm">
            <Search size={14} className="text-muted-foreground" />
            <input
              type="text"
              placeholder="Search by name, phone or email…"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="bg-transparent text-sm text-foreground placeholder:text-muted-foreground outline-none w-full"
            />
          </div>
        </div>

        {/* Table */}
        <div className="card-elevated rounded-xl overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-muted/50 border-b border-border">
                  <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Customer</th>
                  <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Contact</th>
                  <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Location</th>
                  <th className="text-right px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Purchases</th>
                  <th className="text-right px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Total Spent</th>
                  <th className="text-right px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Points</th>
                  <th className="text-center px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Status</th>
                  <th className="text-center px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {filtered.map((customer) => {
                  const sc = statusConfig[customer.status];
                  return (
                    <tr key={customer.id} className="hover:bg-muted/30 transition-colors">
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2.5">
                          <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0">
                            <span className="text-xs font-700 text-primary">{customer.name.split(' ').map((n) => n[0]).join('')}</span>
                          </div>
                          <div>
                            <p className="font-600 text-foreground">{customer.name}</p>
                            <p className="text-xs text-muted-foreground">{customer.id} · Last: {customer.lastVisit}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <div className="space-y-0.5">
                          <div className="flex items-center gap-1 text-xs text-muted-foreground"><Phone size={11} />{customer.phone}</div>
                          <div className="flex items-center gap-1 text-xs text-muted-foreground"><Mail size={11} />{customer.email}</div>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-sm text-muted-foreground">{customer.location}</td>
                      <td className="px-4 py-3 text-right font-tabular font-600 text-foreground">{customer.totalPurchases}</td>
                      <td className="px-4 py-3 text-right font-tabular font-600 text-foreground">KES {customer.totalSpent.toLocaleString()}</td>
                      <td className="px-4 py-3 text-right">
                        <div className="flex items-center justify-end gap-1">
                          <Star size={12} className="text-warning" />
                          <span className="font-tabular font-600 text-foreground">{customer.loyaltyPoints.toLocaleString()}</span>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-center">
                        <span className={`text-xs px-2 py-0.5 rounded-full font-600 ${sc.className}`}>{sc.label}</span>
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex items-center justify-center gap-1">
                          <button className="p-1.5 rounded hover:bg-info-bg text-muted-foreground hover:text-info transition-colors"><Eye size={14} /></button>
                          <button className="p-1.5 rounded hover:bg-warning-bg text-muted-foreground hover:text-warning transition-colors"><Edit2 size={14} /></button>
                          <button className="p-1.5 rounded hover:bg-danger-bg text-muted-foreground hover:text-danger transition-colors"><Trash2 size={14} /></button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          <div className="px-4 py-3 border-t border-border">
            <p className="text-xs text-muted-foreground">Showing {filtered.length} of {customers.length} customers</p>
          </div>
        </div>

        {/* Add Customer Modal */}
        {showModal && (
          <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
            <div className="bg-card rounded-xl shadow-xl w-full max-w-lg p-6 fade-in">
              <div className="flex items-center justify-between mb-5">
                <h2 className="text-base font-700 text-foreground">Add New Customer</h2>
                <button onClick={() => setShowModal(false)} className="p-1.5 rounded hover:bg-muted text-muted-foreground">✕</button>
              </div>
              <div className="grid grid-cols-2 gap-4">
                {[
                  { label: 'Full Name', placeholder: 'Grace Wanjiku', span: 2 },
                  { label: 'Phone Number', placeholder: '+254 7XX XXX XXX' },
                  { label: 'Email Address', placeholder: 'grace@gmail.com' },
                  { label: 'Location / Town', placeholder: 'Westlands, Nairobi', span: 2 },
                  { label: 'ID / Passport No.', placeholder: '12345678' },
                  { label: 'Customer Type', placeholder: 'Regular / VIP / Wholesale' },
                ].map((f) => (
                  <div key={f.label} className={f.span === 2 ? 'col-span-2' : ''}>
                    <label className="block text-xs font-600 text-foreground mb-1">{f.label}</label>
                    <input placeholder={f.placeholder} className="w-full h-9 px-3 text-sm bg-background border border-border rounded-md outline-none focus:border-primary text-foreground placeholder:text-muted-foreground" />
                  </div>
                ))}
              </div>
              <div className="flex gap-3 mt-6">
                <button onClick={() => setShowModal(false)} className="flex-1 h-9 rounded-md border border-border text-sm text-muted-foreground hover:bg-muted transition-colors">Cancel</button>
                <button onClick={() => setShowModal(false)} className="flex-1 h-9 rounded-md btn-primary text-sm font-600 text-white">Save Customer</button>
              </div>
            </div>
          </div>
        )}
      </div>
    </AppLayout>
  );
}
