'use client';

import { useState } from 'react';
import { Store, Plus, Search, Eye, Edit, Trash2, X, MapPin, Phone, Mail, User, DollarSign, Bike, FileText, Clock, CheckCircle, XCircle } from 'lucide-react';
import Link from 'next/link';

type MerchantStatus = 'pending' | 'verified' | 'suspended';
type MerchantTier = 'basic' | 'silver' | 'gold' | 'platinum';

interface Merchant {
  id: string;
  name: string;
  shopName: string;
  email: string;
  phone: string;
  address: string;
  city: string;
  status: MerchantStatus;
  tier: MerchantTier;
  kycStatus: 'pending' | 'approved' | 'rejected';
  bikersAssigned: number;
  bikesRequested: number;
  totalEarnings: number;
  pendingPayment: number;
  joinedAt: string;
}

const mockMerchants: Merchant[] = [
  {
    id: 'MCH-001',
    name: 'Rahim Ahmed',
    shopName: 'Rahim Delivery Service',
    email: 'rahim@delivery.com',
    phone: '+8801712345678',
    address: 'House 12, Road 5, Gulshan 1',
    city: 'Dhaka',
    status: 'verified',
    tier: 'gold',
    kycStatus: 'approved',
    bikersAssigned: 5,
    bikesRequested: 5,
    totalEarnings: 250000,
    pendingPayment: 15000,
    joinedAt: '2024-01-15'
  },
  {
    id: 'MCH-002',
    name: 'Karim Hasan',
    shopName: 'Karim Express',
    email: 'karim@express.com',
    phone: '+8801812345678',
    address: 'House 8, Road 11, Banani',
    city: 'Dhaka',
    status: 'pending',
    tier: 'basic',
    kycStatus: 'pending',
    bikersAssigned: 0,
    bikesRequested: 3,
    totalEarnings: 0,
    pendingPayment: 0,
    joinedAt: '2024-02-01'
  },
  {
    id: 'MCH-003',
    name: 'Jamal Uddin',
    shopName: 'Jamal Logistics',
    email: 'jamal@logistics.com',
    phone: '+8801912345678',
    address: 'Sector 10, Uttara',
    city: 'Dhaka',
    status: 'verified',
    tier: 'platinum',
    kycStatus: 'approved',
    bikersAssigned: 12,
    bikesRequested: 10,
    totalEarnings: 580000,
    pendingPayment: 45000,
    joinedAt: '2023-11-20'
  },
  {
    id: 'MCH-004',
    name: 'Rashid Mia',
    shopName: 'Rashid Delivery',
    email: 'rashid@delivery.com',
    phone: '+8801512345678',
    address: 'Section 10, Mirpur',
    city: 'Dhaka',
    status: 'suspended',
    tier: 'silver',
    kycStatus: 'rejected',
    bikersAssigned: 2,
    bikesRequested: 2,
    totalEarnings: 45000,
    pendingPayment: 0,
    joinedAt: '2024-01-05'
  }
];

const tierColors: Record<MerchantTier, string> = {
  basic: 'bg-slate-100 text-slate-700',
  silver: 'bg-gray-200 text-gray-700',
  gold: 'bg-yellow-100 text-yellow-700',
  platinum: 'bg-purple-100 text-purple-700'
};

const statusColors: Record<MerchantStatus, string> = {
  pending: 'bg-amber-100 text-amber-700',
  verified: 'bg-green-100 text-green-700',
  suspended: 'bg-red-100 text-red-700'
};

const kycColors: Record<string, string> = {
  pending: 'bg-amber-100 text-amber-700',
  approved: 'bg-green-100 text-green-700',
  rejected: 'bg-red-100 text-red-700'
};

const statusLabels: Record<MerchantStatus, string> = {
  pending: 'Pending',
  verified: 'Verified',
  suspended: 'Suspended'
};

const tierLabels: Record<MerchantTier, string> = {
  basic: 'Basic',
  silver: 'Silver',
  gold: 'Gold',
  platinum: 'Platinum'
};

const kycLabels: Record<string, string> = {
  pending: 'Pending',
  approved: 'Approved',
  rejected: 'Rejected'
};

export default function MerchantsPage() {
  const [merchants, setMerchants] = useState<Merchant[]>(mockMerchants);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [editingMerchant, setEditingMerchant] = useState<Merchant | null>(null);
  
  const [formData, setFormData] = useState({
    name: '',
    shopName: '',
    email: '',
    phone: '',
    address: '',
    city: 'Dhaka',
    tier: 'basic' as MerchantTier,
  });

  const filteredMerchants = merchants.filter(m => {
    const matchesSearch = m.name.toLowerCase().includes(search.toLowerCase()) ||
      m.shopName.toLowerCase().includes(search.toLowerCase()) ||
      m.phone.includes(search) ||
      m.id.toLowerCase().includes(search.toLowerCase());
    const matchesStatus = statusFilter === 'all' || m.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  const stats = {
    total: merchants.length,
    verified: merchants.filter(m => m.status === 'verified').length,
    pending: merchants.filter(m => m.status === 'pending').length,
    totalBikers: merchants.reduce((a, m) => a + m.bikersAssigned, 0),
  };

  const handleSave = () => {
    if (!formData.name || !formData.shopName || !formData.phone) return;
    
    if (editingMerchant) {
      setMerchants(merchants.map(m => m.id === editingMerchant.id ? { ...m, ...formData } : m));
    } else {
      const newMerchant: Merchant = {
        id: `MCH-${String(merchants.length + 1).padStart(3, '0')}`,
        ...formData,
        status: 'pending',
        kycStatus: 'pending',
        bikersAssigned: 0,
        bikesRequested: 0,
        totalEarnings: 0,
        pendingPayment: 0,
        joinedAt: new Date().toISOString().split('T')[0],
      };
      setMerchants([...merchants, newMerchant]);
    }
    
    setShowCreateModal(false);
    setEditingMerchant(null);
    setFormData({ name: '', shopName: '', email: '', phone: '', address: '', city: 'Dhaka', tier: 'basic' });
  };

  const handleDelete = (id: string) => {
    if (confirm('Are you sure you want to delete this merchant?')) {
      setMerchants(merchants.filter(m => m.id !== id));
    }
  };

  const openEdit = (merchant: Merchant) => {
    setEditingMerchant(merchant);
    setFormData({
      name: merchant.name,
      shopName: merchant.shopName,
      email: merchant.email,
      phone: merchant.phone,
      address: merchant.address,
      city: merchant.city,
      tier: merchant.tier,
    });
    setShowCreateModal(true);
  };

  return (
    <div className="p-4 lg:p-6">
      <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl lg:text-3xl font-extrabold text-slate-800">Merchants (P2)</h1>
          <p className="text-sm text-slate-500 mt-1">Manage merchant partners and fleet requests</p>
        </div>
        <button 
          onClick={() => {
            setEditingMerchant(null);
            setFormData({ name: '', shopName: '', email: '', phone: '', address: '', city: 'Dhaka', tier: 'basic' });
            setShowCreateModal(true);
          }}
          className="py-2.5 px-4 bg-accent text-white rounded-lg font-semibold text-sm hover:bg-accent-dark transition-colors flex items-center gap-2"
        >
          <Plus className="w-4 h-4" /> Add Merchant
        </button>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <p className="text-2xl font-extrabold text-slate-800">{stats.total}</p>
          <p className="text-sm text-slate-500">Total Merchants</p>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <p className="text-2xl font-extrabold text-green-600">{stats.verified}</p>
          <p className="text-sm text-slate-500">Verified</p>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <p className="text-2xl font-extrabold text-amber-600">{stats.pending}</p>
          <p className="text-sm text-slate-500">Pending</p>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <p className="text-2xl font-extrabold text-blue-600">{stats.totalBikers}</p>
          <p className="text-sm text-slate-500">Bikers Assigned</p>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-slate-100">
        <div className="p-4 border-b border-slate-100">
          <div className="flex flex-col lg:flex-row gap-4">
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
              <input 
                type="text" 
                placeholder="Search by name, shop, phone, ID..." 
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="w-full pl-10 pr-4 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent"
              />
            </div>
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="py-2 px-4 border border-slate-200 rounded-lg text-sm"
            >
              <option value="all">All Status</option>
              <option value="pending">Pending</option>
              <option value="verified">Verified</option>
              <option value="suspended">Suspended</option>
            </select>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-slate-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Merchant</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Shop</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Contact</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Bikers</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Earnings</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">KYC</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Status</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50">
              {filteredMerchants.map(merchant => (
                <tr key={merchant.id} className="hover:bg-slate-50 transition-colors">
                  <td className="px-4 py-3">
                    <Link href={`/admin/merchants/${merchant.id}`} className="hover:text-accent">
                      <div>
                        <span className="text-sm font-medium text-slate-700">{merchant.name}</span>
                        <p className="text-xs text-slate-400">{merchant.id}</p>
                      </div>
                    </Link>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <Store className="w-4 h-4 text-slate-400" />
                      <span className="text-sm text-slate-600">{merchant.shopName}</span>
                    </div>
                    <span className={`text-xs px-2 py-0.5 rounded-full ${tierColors[merchant.tier]}`}>
                      {tierLabels[merchant.tier]}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <p className="text-sm text-slate-600">{merchant.phone}</p>
                    <p className="text-xs text-slate-400">{merchant.city}</p>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <Bike className="w-4 h-4 text-blue-400" />
                      <span className="text-sm font-medium text-slate-700">{merchant.bikersAssigned}/{merchant.bikesRequested}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <p className="text-sm font-medium text-green-600">৳{merchant.totalEarnings.toLocaleString()}</p>
                    {merchant.pendingPayment > 0 && (
                      <p className="text-xs text-amber-600">Pending: ৳{merchant.pendingPayment.toLocaleString()}</p>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    <span className={`text-xs font-medium px-2 py-1 rounded-full ${kycColors[merchant.kycStatus]}`}>
                      {kycLabels[merchant.kycStatus]}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`text-xs font-medium px-2 py-1 rounded-full ${statusColors[merchant.status]}`}>
                      {statusLabels[merchant.status]}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1">
                      <Link href={`/admin/merchants/${merchant.id}`} className="p-2 hover:bg-slate-100 rounded-lg">
                        <Eye className="w-4 h-4 text-slate-400" />
                      </Link>
                      <button onClick={() => openEdit(merchant)} className="p-2 hover:bg-slate-100 rounded-lg">
                        <Edit className="w-4 h-4 text-slate-400" />
                      </button>
                      <button onClick={() => handleDelete(merchant.id)} className="p-2 hover:bg-red-50 rounded-lg">
                        <Trash2 className="w-4 h-4 text-red-400" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {showCreateModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
            <div className="p-4 border-b border-slate-100 flex justify-between items-center sticky top-0 bg-white">
              <h3 className="font-semibold text-slate-800">{editingMerchant ? 'Edit Merchant' : 'Add New Merchant'}</h3>
              <button onClick={() => setShowCreateModal(false)} className="text-slate-400 hover:text-slate-600">
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-4 space-y-4">
              <div>
                <label className="text-sm text-slate-600">Owner Name *</label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  placeholder="Full name"
                />
              </div>
              <div>
                <label className="text-sm text-slate-600">Shop Name *</label>
                <input
                  type="text"
                  value={formData.shopName}
                  onChange={(e) => setFormData({ ...formData, shopName: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  placeholder="Business name"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm text-slate-600">Phone *</label>
                  <input
                    type="text"
                    value={formData.phone}
                    onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                    placeholder="+8801xxxxxxxxx"
                  />
                </div>
                <div>
                  <label className="text-sm text-slate-600">Email</label>
                  <input
                    type="email"
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                    placeholder="email@example.com"
                  />
                </div>
              </div>
              <div>
                <label className="text-sm text-slate-600">Address</label>
                <textarea
                  value={formData.address}
                  onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  rows={2}
                  placeholder="Full address"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm text-slate-600">City</label>
                  <select
                    value={formData.city}
                    onChange={(e) => setFormData({ ...formData, city: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  >
                    <option value="Dhaka">Dhaka</option>
                    <option value="Chittagong">Chittagong</option>
                    <option value="Sylhet">Sylhet</option>
                    <option value="Khulna">Khulna</option>
                  </select>
                </div>
                <div>
                  <label className="text-sm text-slate-600">Tier</label>
                  <select
                    value={formData.tier}
                    onChange={(e) => setFormData({ ...formData, tier: e.target.value as MerchantTier })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  >
                    <option value="basic">Basic</option>
                    <option value="silver">Silver</option>
                    <option value="gold">Gold</option>
                    <option value="platinum">Platinum</option>
                  </select>
                </div>
              </div>
            </div>
            <div className="p-4 border-t border-slate-100 flex justify-end gap-2 sticky bottom-0 bg-white">
              <button 
                onClick={() => setShowCreateModal(false)} 
                className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg text-sm"
              >
                Cancel
              </button>
              <button 
                onClick={handleSave}
                disabled={!formData.name || !formData.shopName || !formData.phone}
                className="px-4 py-2 bg-accent text-white rounded-lg text-sm disabled:opacity-50"
              >
                {editingMerchant ? 'Update' : 'Create'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}