'use client';

import { useState, use } from 'react';
import { Store, ArrowLeft, Phone, Mail, MapPin, User, Bike, DollarSign, Clock, FileText, CheckCircle, XCircle, AlertCircle, Edit, Trash2, Plus, X, Upload } 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;
}

interface Rental {
  id: string;
  bikeName: string;
  biker: string;
  startDate: string;
  endDate: string;
  amount: number;
  status: 'active' | 'pending' | 'completed' | 'cancelled';
  type: 'daily' | 'monthly';
}

const mockMerchant: 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'
};

const mockRentals: Rental[] = [
  { id: 'RNT-001', bikeName: 'Yamaha NMAX', biker: 'Karim Khan', startDate: '2024-01-20', endDate: '2024-02-20', amount: 5000, status: 'completed', type: 'monthly' },
  { id: 'RNT-002', bikeName: 'Honda PCX', biker: 'Jamal Mia', startDate: '2024-02-01', endDate: '2024-03-01', amount: 5500, status: 'active', type: 'monthly' },
  { id: 'RNT-003', bikeName: 'TVS Ntorq', biker: 'Rashid Ali', startDate: '2024-02-15', endDate: '2024-03-15', amount: 4500, status: 'active', type: 'monthly' },
  { id: 'RNT-004', bikeName: 'Suzuki Burgman', biker: 'New Request', startDate: '-', endDate: '-', amount: 5000, status: 'pending', type: 'monthly' },
];

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

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

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 rentalStatusColors: Record<string, string> = {
  active: 'bg-green-100 text-green-700',
  pending: 'bg-amber-100 text-amber-700',
  completed: 'bg-blue-100 text-blue-700',
  cancelled: 'bg-red-100 text-red-700'
};

export default function MerchantDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const [merchant] = useState<Merchant>(mockMerchant);
  const [activeTab, setActiveTab] = useState<'overview' | 'rentals' | 'payments'>('overview');

  const stats = [
    { label: 'Bikers Assigned', value: merchant.bikersAssigned, icon: Bike, color: 'text-blue-600' },
    { label: 'Bikes Requested', value: merchant.bikesRequested, icon: Plus, color: 'text-purple-600' },
    { label: 'Total Earnings', value: `৳${merchant.totalEarnings.toLocaleString()}`, icon: DollarSign, color: 'text-green-600' },
    { label: 'Pending Payment', value: `৳${merchant.pendingPayment.toLocaleString()}`, icon: Clock, color: 'text-amber-600' },
  ];

  return (
    <div className="p-4 lg:p-6">
      <div className="flex items-center gap-4 mb-6">
        <Link href="/admin/merchants" className="p-2 hover:bg-slate-100 rounded-lg">
          <ArrowLeft className="w-5 h-5 text-slate-600" />
        </Link>
        <div className="flex-1">
          <h1 className="text-xl lg:text-2xl font-extrabold text-slate-800">{merchant.shopName}</h1>
          <p className="text-sm text-slate-500">{merchant.id} • Joined {merchant.joinedAt}</p>
        </div>
        <div className="flex gap-2">
          <button className="py-2 px-4 border border-slate-200 text-slate-600 rounded-lg text-sm hover:bg-slate-50 flex items-center gap-2">
            <Edit className="w-4 h-4" /> Edit
          </button>
          <button className="py-2 px-4 bg-red-500 text-white rounded-lg text-sm hover:bg-red-600 flex items-center gap-2">
            <Trash2 className="w-4 h-4" /> Delete
          </button>
        </div>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        {stats.map((stat, i) => (
          <div key={i} className="bg-white rounded-xl p-4 shadow-sm border border-slate-100">
            <div className="flex items-center gap-3">
              <div className={`p-2 rounded-lg bg-slate-50 ${stat.color}`}>
                <stat.icon className="w-5 h-5" />
              </div>
              <div>
                <p className="text-lg font-bold text-slate-800">{stat.value}</p>
                <p className="text-xs text-slate-500">{stat.label}</p>
              </div>
            </div>
          </div>
        ))}
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-slate-100 mb-6">
        <div className="flex gap-6 p-4 border-b border-slate-100">
          {(['overview', 'rentals', 'payments'] as const).map(tab => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              className={`text-sm font-medium pb-2 border-b-2 transition-colors ${
                activeTab === tab 
                  ? 'text-accent border-accent' 
                  : 'text-slate-500 border-transparent hover:text-slate-700'
              }`}
            >
              {tab.charAt(0).toUpperCase() + tab.slice(1)}
            </button>
          ))}
        </div>

        {activeTab === 'overview' && (
          <div className="p-4 space-y-6">
            <div className="grid lg:grid-cols-2 gap-6">
              <div className="space-y-4">
                <h3 className="font-semibold text-slate-800">Business Information</h3>
                <div className="space-y-3">
                  <div className="flex items-center gap-3">
                    <Store className="w-4 h-4 text-slate-400" />
                    <span className="text-sm text-slate-600">{merchant.shopName}</span>
                  </div>
                  <div className="flex items-center gap-3">
                    <User className="w-4 h-4 text-slate-400" />
                    <span className="text-sm text-slate-600">{merchant.name}</span>
                    <span className={`text-xs px-2 py-0.5 rounded-full border ${tierColors[merchant.tier]}`}>
                      {merchant.tier.toUpperCase()}
                    </span>
                  </div>
                  <div className="flex items-center gap-3">
                    <span className="text-xs px-2 py-1 rounded-full border bg-slate-50 text-slate-600">Status</span>
                    <span className={`text-xs px-2 py-1 rounded-full border ${statusColors[merchant.status]}`}>
                      {merchant.status.toUpperCase()}
                    </span>
                  </div>
                </div>
              </div>

              <div className="space-y-4">
                <h3 className="font-semibold text-slate-800">Contact Information</h3>
                <div className="space-y-3">
                  <div className="flex items-center gap-3">
                    <Phone className="w-4 h-4 text-slate-400" />
                    <span className="text-sm text-slate-600">{merchant.phone}</span>
                  </div>
                  <div className="flex items-center gap-3">
                    <Mail className="w-4 h-4 text-slate-400" />
                    <span className="text-sm text-slate-600">{merchant.email}</span>
                  </div>
                  <div className="flex items-center gap-3">
                    <MapPin className="w-4 h-4 text-slate-400" />
                    <span className="text-sm text-slate-600">{merchant.address}, {merchant.city}</span>
                  </div>
                </div>
              </div>
            </div>

            <div className="grid lg:grid-cols-2 gap-6 pt-4 border-t border-slate-100">
              <div className="space-y-4">
                <h3 className="font-semibold text-slate-800">KYC Status</h3>
                <div className="flex items-center gap-3">
                  {merchant.kycStatus === 'approved' ? (
                    <CheckCircle className="w-5 h-5 text-green-500" />
                  ) : merchant.kycStatus === 'rejected' ? (
                    <XCircle className="w-5 h-5 text-red-500" />
                  ) : (
                    <AlertCircle className="w-5 h-5 text-amber-500" />
                  )}
                  <span className={`text-sm px-3 py-1 rounded-full ${kycColors[merchant.kycStatus]}`}>
                    {merchant.kycStatus.toUpperCase()}
                  </span>
                </div>
              </div>

              <div className="space-y-4">
                <h3 className="font-semibold text-slate-800">Documents</h3>
                <div className="space-y-2">
                  <button className="w-full flex items-center justify-between p-3 border border-slate-200 rounded-lg hover:bg-slate-50">
                    <div className="flex items-center gap-2">
                      <FileText className="w-4 h-4 text-slate-400" />
                      <span className="text-sm text-slate-600">Trade License</span>
                    </div>
                    <span className="text-xs text-green-600">Uploaded</span>
                  </button>
                  <button className="w-full flex items-center justify-between p-3 border border-slate-200 rounded-lg hover:bg-slate-50">
                    <div className="flex items-center gap-2">
                      <FileText className="w-4 h-4 text-slate-400" />
                      <span className="text-sm text-slate-600">NID Copy</span>
                    </div>
                    <span className="text-xs text-green-600">Uploaded</span>
                  </button>
                  <button className="w-full flex items-center justify-between p-3 border border-slate-200 rounded-lg hover:bg-slate-50">
                    <div className="flex items-center gap-2">
                      <FileText className="w-4 h-4 text-slate-400" />
                      <span className="text-sm text-slate-600">TIN Certificate</span>
                    </div>
                    <span className="text-xs text-amber-600">Pending</span>
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}

        {activeTab === 'rentals' && (
          <div className="p-4">
            <div className="flex justify-between items-center mb-4">
              <h3 className="font-semibold text-slate-800">Active Rentals</h3>
              <button className="py-2 px-4 bg-accent text-white rounded-lg text-sm flex items-center gap-2">
                <Plus className="w-4 h-4" /> Request Bike
              </button>
            </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">Rental ID</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Bike</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Biker</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Period</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Amount</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">Action</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-50">
                  {mockRentals.map(rental => (
                    <tr key={rental.id} className="hover:bg-slate-50">
                      <td className="px-4 py-3 text-sm font-medium text-slate-700">{rental.id}</td>
                      <td className="px-4 py-3 text-sm text-slate-600">{rental.bikeName}</td>
                      <td className="px-4 py-3 text-sm text-slate-600">{rental.biker}</td>
                      <td className="px-4 py-3 text-sm text-slate-600">
                        {rental.startDate === '-' ? '-' : `${rental.startDate} to ${rental.endDate}`}
                      </td>
                      <td className="px-4 py-3 text-sm font-medium text-green-600">৳{rental.amount.toLocaleString()}</td>
                      <td className="px-4 py-3">
                        <span className={`text-xs px-2 py-1 rounded-full ${rentalStatusColors[rental.status]}`}>
                          {rental.status.charAt(0).toUpperCase() + rental.status.slice(1)}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        {rental.status === 'pending' ? (
                          <button className="text-xs text-accent hover:underline">Approve</button>
                        ) : (
                          <Link href={`/admin/rentals/${rental.id}`} className="text-xs text-accent hover:underline">View</Link>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {activeTab === 'payments' && (
          <div className="p-4">
            <div className="flex justify-between items-center mb-4">
              <h3 className="font-semibold text-slate-800">Payment History</h3>
              <button className="py-2 px-4 border border-accent text-accent rounded-lg text-sm flex items-center gap-2">
                <DollarSign className="w-4 h-4" /> Make Payment
              </button>
            </div>
            <div className="text-center py-12 text-slate-500">
              <DollarSign className="w-12 h-12 mx-auto mb-4 text-slate-300" />
              <p className="text-sm">No payment records found</p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}