'use client';

import { useState } from 'react';
import Link from 'next/link';
import { investors as initialInvestors, bikes as initialBikes } from '@/data/mockData';
import type { Investor } from '@/data/mockData';

type InvestorWithImage = Investor & { profileImage: string };
import { Search, Download, Upload, Edit, Trash2, X, LayoutGrid, List, Phone, Mail, Wallet, TrendingUp, Banknote, Bike, Eye } from 'lucide-react';
import toast from 'react-hot-toast';

const statusColors: Record<string, string> = {
  active: 'bg-green-100 text-green-700',
  pending: 'bg-amber-100 text-amber-700',
  inactive: 'bg-slate-100 text-slate-500',
  suspended: 'bg-red-100 text-red-700',
};

const planColors: Record<string, string> = {
  silver: 'bg-slate-200 text-slate-700',
  gold: 'bg-yellow-100 text-yellow-700',
  platinum: 'bg-purple-100 text-purple-700',
  diamond: 'bg-blue-100 text-blue-700',
};

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

const investorsWithImages = initialInvestors.map((inv, idx) => ({
  ...inv,
  profileImage: `https://picsum.photos/200/200?random=${idx + 1}`,
}));

export default function InvestorsPage() {
  const [investors, setInvestors] = useState<InvestorWithImage[]>(investorsWithImages as InvestorWithImage[]);
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [kycFilter, setKycFilter] = useState('all');
  const [viewMode, setViewMode] = useState<'table' | 'cards'>('table');
  const [deleteModal, setDeleteModal] = useState<{ show: boolean; investor: InvestorWithImage | null }>({ show: false, investor: null });

  const filteredInvestors = investors.filter(inv => {
    const matchesSearch = inv.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      inv.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
      inv.phone.includes(searchQuery);
    const matchesStatus = statusFilter === 'all' || inv.status === statusFilter;
    const matchesKyc = kycFilter === 'all' || inv.kycStatus === kycFilter;
    return matchesSearch && matchesStatus && matchesKyc;
  });

  const handleDeleteInvestor = () => {
    if (deleteModal.investor) {
      setInvestors(investors.filter(i => i.id !== deleteModal.investor!.id));
      setDeleteModal({ show: false, investor: null });
      toast.success('Investor deleted successfully');
    }
  };

  const getInitials = (name: string) => {
    return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2);
  };

  const isMobile = typeof window !== 'undefined' && window.innerWidth < 1024;

  return (
    <div className="p-4 lg:p-6">
      <div className="mb-6">
        <h1 className="text-2xl lg:text-3xl font-extrabold text-slate-800">Investors</h1>
        <p className="text-sm text-slate-500 mt-1">Manage investor accounts and investments</p>
      </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">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-purple-50 flex items-center justify-center">
              <Wallet className="w-6 h-6 text-purple-600" />
            </div>
            <div>
              <p className="text-2xl font-extrabold text-slate-800">{investors.reduce((sum, i) => sum + i.totalInvested, 0).toLocaleString()}</p>
              <p className="text-sm text-slate-500">Total Invested</p>
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-green-50 flex items-center justify-center">
              <TrendingUp className="w-6 h-6 text-green-600" />
            </div>
            <div>
              <p className="text-2xl font-extrabold text-slate-800">{investors.reduce((sum, i) => sum + i.totalEarnings, 0).toLocaleString()}</p>
              <p className="text-sm text-slate-500">Total Earnings</p>
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-blue-50 flex items-center justify-center">
              <Bike className="w-6 h-6 text-blue-600" />
            </div>
            <div>
              <p className="text-2xl font-extrabold text-slate-800">{investors.reduce((sum, i) => sum + i.activeBikes, 0)}</p>
              <p className="text-sm text-slate-500">Active Bikes</p>
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-amber-50 flex items-center justify-center">
              <Banknote className="w-6 h-6 text-amber-600" />
            </div>
            <div>
              <p className="text-2xl font-extrabold text-slate-800">{investors.length}</p>
              <p className="text-sm text-slate-500">Total Investors</p>
            </div>
          </div>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-slate-100">
        <div className="p-4 border-b border-slate-100 flex flex-col lg:flex-row lg:items-center gap-3">
          <div className="relative flex-1">
            <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, email, phone..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-2.5 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent"
            />
          </div>
          <div className="flex items-center gap-2 flex-wrap">
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="py-2.5 px-3 border border-slate-200 rounded-lg text-sm font-medium text-slate-600 bg-white"
            >
              <option value="all">All Status</option>
              <option value="active">Active</option>
              <option value="pending">Pending</option>
              <option value="inactive">Inactive</option>
              <option value="suspended">Suspended</option>
            </select>
            <select
              value={kycFilter}
              onChange={(e) => setKycFilter(e.target.value)}
              className="py-2.5 px-3 border border-slate-200 rounded-lg text-sm font-medium text-slate-600 bg-white"
            >
              <option value="all">All KYC</option>
              <option value="verified">Verified</option>
              <option value="pending">Pending</option>
            </select>
            <button
              onClick={() => setViewMode(viewMode === 'table' ? 'cards' : 'table')}
              className="py-2.5 px-3 border border-slate-200 rounded-lg text-sm font-medium text-slate-600 hover:bg-slate-50 flex items-center gap-2"
            >
              <LayoutGrid className="w-4 h-4" />
              {viewMode === 'table' ? 'Cards' : 'Table'}
            </button>
            <button className="py-2.5 px-3 border border-slate-200 rounded-lg text-sm font-medium text-slate-600 hover:bg-slate-50 flex items-center gap-2">
              <Download className="w-4 h-4" /> Export
            </button>
            <button className="py-2.5 px-3 border border-slate-200 rounded-lg text-sm font-medium text-slate-600 hover:bg-slate-50 flex items-center gap-2">
              <Upload className="w-4 h-4" /> Import
            </button>
          </div>
        </div>

        {(viewMode === 'cards' || isMobile) ? (
          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 p-4">
            {filteredInvestors.map(inv => (
              <div key={inv.id} className="bg-white rounded-xl border border-slate-200 p-5 hover:shadow-lg transition-shadow">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-center gap-3">
                    {inv.profileImage ? (
                      <img
                        src={inv.profileImage}
                        alt={inv.name}
                        className="w-12 h-12 rounded-full object-cover"
                      />
                    ) : (
                      <div className="w-12 h-12 rounded-full bg-purple-100 flex items-center justify-center">
                        <span className="text-sm font-bold text-purple-600">{getInitials(inv.name)}</span>
                      </div>
                    )}
                    <div>
                      <p className="font-semibold text-slate-800">{inv.name}</p>
                      <p className="text-xs text-slate-400">{inv.id}</p>
                    </div>
                  </div>
                </div>

                <div className="flex flex-wrap gap-2 mb-4">
                  <span className={`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full capitalize ${kycColors[inv.kycStatus]}`}>
                    {inv.kycStatus}
                  </span>
                  <span className={`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full capitalize ${statusColors[inv.status]}`}>
                    {inv.status}
                  </span>
                </div>

                <div className="space-y-2 mb-4">
                  <div className="flex items-center gap-2 text-sm text-slate-500">
                    <Phone className="w-4 h-4" />
                    <span>{inv.phone}</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm text-slate-500">
                    <Mail className="w-4 h-4" />
                    <span className="truncate">{inv.email}</span>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-3 mb-4">
                  <div className="bg-slate-50 rounded-lg p-3">
                    <p className="text-xs text-slate-400">Investment</p>
                    <p className="font-semibold text-purple-600">৳{inv.totalInvested.toLocaleString()}</p>
                  </div>
                  <div className="bg-slate-50 rounded-lg p-3">
                    <p className="text-xs text-slate-400">Earnings</p>
                    <p className="font-semibold text-green-600">৳{inv.totalEarnings.toLocaleString()}</p>
                  </div>
                  <div className="bg-slate-50 rounded-lg p-3">
                    <p className="text-xs text-slate-400">ROI</p>
                    <p className="font-semibold text-slate-700">{inv.roi}%</p>
                  </div>
                  <div className="bg-slate-50 rounded-lg p-3">
                    <p className="text-xs text-slate-400">Bikes</p>
                    <p className="font-semibold text-slate-700">{inv.activeBikes}</p>
                  </div>
                  <div className="bg-slate-50 rounded-lg p-3">
                    <p className="text-xs text-slate-400">Plans</p>
                    <p className="font-semibold text-slate-700">{inv.investments?.length || 0}</p>
                  </div>
                  <div className="bg-slate-50 rounded-lg p-3">
                    <p className="text-xs text-slate-400">Plan Type</p>
                    <span className={`inline-flex text-xs font-medium px-2 py-0.5 rounded-full capitalize ${planColors[inv.investments?.[0]?.planType || 'silver']}`}>
                      {inv.investments?.[0]?.planType || 'silver'}
                    </span>
                  </div>
                </div>

                <div className="flex items-center gap-2 pt-3 border-t border-slate-100">
                  <Link
                    href={`/admin/investors/${inv.id}`}
                    className="flex-1 py-2 px-3 bg-slate-100 text-slate-600 rounded-lg text-sm font-medium hover:bg-slate-200 text-center"
                  >
                    View Details
                  </Link>
                  <Link
                    href={`/admin/investors/${inv.id}`}
                    className="p-2 hover:bg-slate-100 rounded-lg"
                    title="Edit"
                  >
                    <Edit className="w-4 h-4 text-slate-400" />
                  </Link>
                  <button
                    onClick={() => setDeleteModal({ show: true, investor: inv })}
                    className="p-2 hover:bg-red-50 rounded-lg"
                    title="Delete"
                  >
                    <Trash2 className="w-4 h-4 text-red-400" />
                  </button>
                </div>
              </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 tracking-wider">Avatar</th> */}
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Investor</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Contact</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Investment</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Earnings</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Bikes</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Plan</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">KYC</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Status</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50">
                {filteredInvestors.map(inv => (
                  <tr key={inv.id} className="hover:bg-slate-50 transition-colors">
                    <td className="px-4 py-3">
                      <Link href={`/admin/investors/${inv.id}`} className="flex items-center gap-3 hover:bg-slate-50 -m-2 p-2 rounded-lg">
                        {inv.profileImage ? (
                          <img
                            src={inv.profileImage}
                            alt={inv.name}
                            className="w-10 h-10 rounded-full object-cover"
                          />
                        ) : (
                          <div className="w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center">
                            <span className="text-sm font-bold text-purple-600">{getInitials(inv.name)}</span>
                          </div>
                        )}
                        <div>
                          <p className="text-sm font-medium text-slate-700">{inv.name}</p>
                          <p className="text-xs text-slate-400">{inv.id}</p>
                        </div>
                      </Link>
                    </td>
                    <td className="px-4 py-3">
                      <div className="text-sm text-slate-600">{inv.phone}</div>
                      <div className="text-xs text-slate-400">{inv.email}</div>
                    </td>
                    <td className="px-4 py-3">
                      <div className="text-sm font-medium text-purple-600">৳{inv.totalInvested.toLocaleString()}</div>
                    </td>
                    <td className="px-4 py-3">
                      <div className="text-sm font-medium text-green-600">৳{inv.totalEarnings.toLocaleString()}</div>
                      <div className="text-xs text-slate-400">ROI: {inv.roi}%</div>
                    </td>
                    <td className="px-4 py-3">
                      <div className="text-sm font-medium text-slate-700">{inv.activeBikes}</div>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full capitalize ${planColors[inv.investments?.[0]?.planType || 'silver']}`}>
                        {inv.investments?.[0]?.planType || 'silver'}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full capitalize ${kycColors[inv.kycStatus]}`}>
                        {inv.kycStatus}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full capitalize ${statusColors[inv.status]}`}>
                        {inv.status}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-1">
                        <Link href={`/admin/investors/${inv.id}`} className="p-2 hover:bg-slate-100 rounded-lg" title="View Details">
                          <Eye className="w-4 h-4 text-slate-400" />
                        </Link>
                        <Link href={`/admin/investors/${inv.id}`} className="p-2 hover:bg-slate-100 rounded-lg" title="Edit">
                          <Edit className="w-4 h-4 text-slate-400" />
                        </Link>
                        <button
                          onClick={() => setDeleteModal({ show: true, investor: inv })}
                          className="p-2 hover:bg-red-50 rounded-lg"
                          title="Delete"
                        >
                          <Trash2 className="w-4 h-4 text-red-400" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {deleteModal.show && deleteModal.investor && (
        <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-md">
            <div className="p-6 text-center">
              <div className="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center mx-auto mb-4">
                <Trash2 className="w-6 h-6 text-red-600" />
              </div>
              <h3 className="text-lg font-bold text-slate-800 mb-2">Delete Investor</h3>
              <p className="text-slate-500 mb-1">
                Are you sure you want to delete <span className="font-semibold text-slate-700">{deleteModal.investor.name}</span>?
              </p>
              <p className="text-sm text-red-500">This action cannot be undone. All investor data will be permanently removed.</p>
            </div>
            <div className="p-4 border-t border-slate-100 flex gap-3">
              <button
                onClick={() => setDeleteModal({ show: false, investor: null })}
                className="flex-1 py-2.5 px-4 border border-slate-200 text-slate-600 rounded-lg text-sm font-medium hover:bg-slate-50"
              >
                Cancel
              </button>
              <button
                onClick={handleDeleteInvestor}
                className="flex-1 py-2.5 px-4 bg-red-500 text-white rounded-lg text-sm font-medium hover:bg-red-600"
              >
                Delete
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}