'use client';

import { useState, use } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import {
  ArrowLeft, TrendingUp, Bike, DollarSign, Calendar,
  CreditCard, FileText, Download, Check,
  Printer, BarChart3, Wallet, Clock, Shield, Percent, Activity, AlertTriangle,
  Receipt, CreditCardIcon, Zap, Smartphone, ChevronRight, Target
} from 'lucide-react';
import { investors, bikes, transactions } from '@/data/mockData';
import toast from 'react-hot-toast';
import InvestorNotification from '@/components/InvestorNotification';

export default function InvestorInvestmentDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const resolvedParams = use(params);
  const { id: investmentId } = resolvedParams;
  const router = useRouter();

  const investor = investors[0]; // mock logged-in investor
  const investment = investor.investments?.find((inv: any) => inv.id === investmentId);

  const [activeTab, setActiveTab] = useState('overview');

  if (!investment) {
    return (
      <div className="p-4 lg:p-6">
        <div className="text-center py-12">
          <h2 className="text-xl font-bold text-slate-800">Investment Not Found</h2>
          <p className="text-slate-500 mt-2">The investment you're looking for doesn't exist.</p>
          <Link href="/investor/portfolio" className="mt-4 inline-flex items-center gap-2 text-investor hover:underline">
            <ArrowLeft className="w-4 h-4" /> Back to Portfolio
          </Link>
        </div>
      </div>
    );
  }

  const planConfig: Record<string, { bg: string; border: string; text: string; badge: string; icon: any }> = {
    silver: { bg: 'bg-slate-50', border: 'border-slate-200', text: 'text-slate-700', badge: 'bg-slate-200 text-slate-700', icon: Zap },
    gold: { bg: 'bg-amber-50', border: 'border-amber-200', text: 'text-amber-700', badge: 'bg-amber-100 text-amber-700', icon: Shield },
    platinum: { bg: 'bg-purple-50', border: 'border-purple-200', text: 'text-purple-700', badge: 'bg-purple-100 text-purple-700', icon: TrendingUp },
    diamond: { bg: 'bg-blue-50', border: 'border-blue-200', text: 'text-blue-700', badge: 'bg-blue-100 text-blue-700', icon: Zap },
  };
  const style = planConfig[investment.planType] || planConfig.gold;

  const assignedBikes = bikes.filter((b: any) => b.investorId === investor.id && b.id === 'b1'); // mock filtering for this investment

  const investmentTransactions = transactions.filter((t: any) => t.investorId === investor.id && t.type === 'investment_return');

  return (
    <div className="min-h-screen ">
      <InvestorNotification isMobile />
      <div className="pt-18 lg:pt-0 p-4 lg:p-6 max-w-6xl mx-auto mb-20 lg:mb-0">
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4 mb-6">
          <div className="flex items-center gap-4">
            <button onClick={() => router.back()} className="p-2 hover:bg-slate-100 rounded-lg transition-colors border border-slate-200">
              <ArrowLeft className="w-5 h-5 text-slate-600" />
            </button>
            <div>
              <div className="flex items-center gap-3">
                <h1 className="text-xl lg:text-2xl font-extrabold text-slate-800 flex items-center gap-2">
                  <Target className="w-5 h-5 lg:w-6 lg:h-6 text-investor" />{investment.planName}</h1>
                <span className={`px-2.5 py-1 rounded-full text-xs font-bold ${style.badge} capitalize`}>
                  {investment.planType} Plan
                </span>
                <span className={`px-2.5 py-1 rounded-full text-xs font-bold ${investment.status === 'active' ? 'bg-green-100 text-green-700' : 'bg-slate-100 text-slate-600'} capitalize`}>
                  {investment.status}
                </span>
              </div>
              <p className="text-slate-500 text-sm mt-1 flex items-center gap-2">
                ID: <span className="font-mono text-xs bg-slate-100 px-1.5 py-0.5 rounded">#{investment.id?.toUpperCase()}</span>
                <span className="text-slate-300">•</span> Started: {investment.startDate}
              </p>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <button onClick={() => toast.success('Statement download started')} className="px-4 py-2 bg-white border border-slate-200 text-slate-700 rounded-xl text-sm font-bold hover:bg-slate-50 flex items-center gap-2 shadow-sm transition-all">
              <Download className="w-4 h-4 text-slate-400" /> Download Statement
            </button>
          </div>
        </div>

        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
          <div className="bg-white rounded-2xl p-5 border border-slate-200 shadow-sm">
            <div className="flex items-center gap-3 mb-3">
              <div className="w-10 h-10 bg-purple-100 rounded-xl flex items-center justify-center">
                <Wallet className="w-5 h-5 text-purple-600" />
              </div>
              <p className="text-sm text-slate-500 font-medium">Invested</p>
            </div>
            <p className="text-2xl font-extrabold text-slate-800">৳{investment.totalInvestment.toLocaleString()}</p>
          </div>
          <div className="bg-white rounded-2xl p-5 border border-slate-200 shadow-sm">
            <div className="flex items-center gap-3 mb-3">
              <div className="w-10 h-10 bg-green-100 rounded-xl flex items-center justify-center">
                <TrendingUp className="w-5 h-5 text-green-600" />
              </div>
              <p className="text-sm text-slate-500 font-medium">Total Return</p>
            </div>
            <p className="text-2xl font-extrabold text-green-600">৳{investment.actualEarnings.toLocaleString()}</p>
          </div>
          <div className="bg-white rounded-2xl p-5 border border-slate-200 shadow-sm">
            <div className="flex items-center gap-3 mb-3">
              <div className="w-10 h-10 bg-amber-100 rounded-xl flex items-center justify-center">
                <Clock className="w-5 h-5 text-amber-600" />
              </div>
              <p className="text-sm text-slate-500 font-medium">Pending</p>
            </div>
            <p className="text-2xl font-extrabold text-amber-600">৳{(investment.totalInvestment * 0.24 - investment.actualEarnings).toLocaleString()}</p>
          </div>
          <div className="bg-white rounded-2xl p-5 border border-slate-200 shadow-sm">
            <div className="flex items-center gap-3 mb-3">
              <div className="w-10 h-10 bg-blue-100 rounded-xl flex items-center justify-center">
                <Percent className="w-5 h-5 text-blue-600" />
              </div>
              <p className="text-sm text-slate-500 font-medium">ROI</p>
            </div>
            <p className="text-2xl font-extrabold text-blue-600">{investment.expectedRoi}%</p>
          </div>
        </div>

        <div className="grid lg:grid-cols-3 gap-6">
          <div className="lg:col-span-2 space-y-6">
            <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
              <div className="flex overflow-x-auto bg-slate-50 border-b border-slate-100">
                {['overview', 'bikes', 'pnl', 'transactions'].map((tab) => (
                  <button
                    key={tab}
                    onClick={() => setActiveTab(tab)}
                    className={`px-6 py-4 text-sm font-bold capitalize transition-colors whitespace-nowrap ${activeTab === tab ? 'text-investor bg-white border-b-2 border-investor' : 'text-slate-500 hover:text-slate-700'}`}
                  >
                    {tab}
                  </button>
                ))}
              </div>

              <div className="p-6">
                {activeTab === 'overview' && (
                  <div className="space-y-6">
                    <div className="grid md:grid-cols-2 gap-4">
                      <div className="bg-slate-50 rounded-2xl p-5 border border-slate-200">
                        <h4 className="font-bold text-slate-800 mb-4 flex items-center gap-2">
                          <FileText className="w-5 h-5 text-slate-400" /> Investment Details
                        </h4>
                        <div className="space-y-3 text-sm">
                          <div className="flex justify-between border-b border-slate-200 pb-2">
                            <span className="text-slate-500">Plan Name</span>
                            <span className="font-bold text-slate-800">{investment.planName}</span>
                          </div>
                          <div className="flex justify-between border-b border-slate-200 pb-2">
                            <span className="text-slate-500">Plan Type</span>
                            <span className="font-bold text-slate-800 capitalize">{investment.planType}</span>
                          </div>
                          <div className="flex justify-between border-b border-slate-200 pb-2">
                            <span className="text-slate-500">Period</span>
                            <span className="font-bold text-slate-800">{investment.startDate} - {investment.endDate || 'Ongoing'}</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-500">Payment Method</span>
                            <span className="font-bold text-slate-800 capitalize">{investment.paymentMethod}</span>
                          </div>
                        </div>
                      </div>

                      <div className="bg-slate-50 rounded-2xl p-5 border border-slate-200">
                        <h4 className="font-bold text-slate-800 mb-4 flex items-center gap-2">
                          <Shield className="w-5 h-5 text-slate-400" /> Plan Policy
                        </h4>
                        <div className="space-y-3 text-sm">
                          <div className="flex justify-between border-b border-slate-200 pb-2">
                            <span className="text-slate-500">Min Duration</span>
                            <span className="font-bold text-slate-800">12 Months</span>
                          </div>
                          <div className="flex justify-between border-b border-slate-200 pb-2">
                            <span className="text-slate-500">Lock-in Period</span>
                            <span className="font-bold text-slate-800">3 Months</span>
                          </div>
                          <div className="flex justify-between border-b border-slate-200 pb-2">
                            <span className="text-slate-500">Exit Penalty</span>
                            <span className="font-bold text-red-500">10%</span>
                          </div>
                          <div className="flex justify-between">
                            <span className="text-slate-500">Maintenance</span>
                            <span className="font-bold text-green-600">Included</span>
                          </div>
                        </div>
                      </div>
                    </div>

                    <div className="bg-amber-50 border border-amber-200 rounded-2xl p-5">
                      <h4 className="font-bold text-amber-800 mb-4 flex items-center gap-2">
                        <Percent className="w-5 h-5 text-amber-600" /> Profit Sharing Configuration
                      </h4>
                      <p className="text-xs text-amber-600 mb-4 uppercase font-bold tracking-wider">Your share based on rental model</p>
                      <div className="grid grid-cols-3 gap-3">
                        <div className="bg-white rounded-xl p-4 text-center border border-amber-200 shadow-sm">
                          <p className="text-xs text-slate-400 mb-1 font-bold uppercase">Single Rent</p>
                          <p className="text-2xl font-extrabold text-slate-800">55%</p>
                        </div>
                        <div className="bg-white rounded-xl p-4 text-center border border-amber-200 shadow-sm">
                          <p className="text-xs text-slate-400 mb-1 font-bold uppercase">Rent to Own</p>
                          <p className="text-2xl font-extrabold text-slate-800">45%</p>
                        </div>
                        <div className="bg-white rounded-xl p-4 text-center border border-amber-200 shadow-sm ring-2 ring-amber-500 ring-offset-2">
                          <p className="text-xs text-slate-400 mb-1 font-bold uppercase">Share EV</p>
                          <p className="text-2xl font-extrabold text-slate-800">40%</p>
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {activeTab === 'bikes' && (
                  <div className="space-y-4">
                    {assignedBikes.length > 0 ? assignedBikes.map(bike => (
                      <div key={bike.id} className="p-5 bg-white rounded-2xl border border-slate-200 flex flex-col md:flex-row items-start md:items-center gap-5 hover:border-investor transition-colors group">
                        <div className="w-20 h-20 bg-slate-100 rounded-xl overflow-hidden shrink-0 border border-slate-200">
                          <img src={bike.image} alt={bike.model} className="w-full h-full object-cover" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <h5 className="font-bold text-lg text-slate-800 truncate">{bike.model}</h5>
                          <p className="text-sm text-slate-500">{bike.plateNumber} • {bike.brand}</p>
                          <div className="mt-3 flex flex-wrap gap-2">
                            <span className={`px-2 py-0.5 rounded text-[10px] font-bold uppercase ${bike.status === 'rented' ? 'bg-green-100 text-green-700' : 'bg-blue-100 text-blue-700'}`}>
                              {bike.status}
                            </span>
                            <span className="px-2 py-0.5 rounded bg-slate-100 text-slate-600 text-[10px] font-bold uppercase flex items-center gap-1">
                              Daily: ৳{bike.currentRent}
                            </span>
                          </div>
                        </div>
                        <div className="text-right">
                          <p className="text-xs text-slate-400 mb-1 uppercase font-bold tracking-wider">Total Earnings</p>
                          <p className="text-xl font-extrabold text-green-600">৳{bike.totalEarnings?.toLocaleString()}</p>
                          <Link href="/investor/portfolio" className="mt-2 text-xs font-bold text-investor hover:underline flex items-center gap-1 justify-end">
                            Live Track <ChevronRight className="w-3 h-3" />
                          </Link>
                        </div>
                      </div>
                    )) : (
                      <div className="text-center py-12 border-2 border-dashed border-slate-200 rounded-2xl">
                        <Bike className="w-12 h-12 mx-auto mb-4 text-slate-300" />
                        <p className="text-slate-500 font-bold">No bikes assigned yet.</p>
                        <p className="text-xs text-slate-400 mt-1">Admin will assign bikes to this investment shortly.</p>
                      </div>
                    )}
                  </div>
                )}

                {activeTab === 'pnl' && (
                  <div className="max-w-xl mx-auto">
                    <div className="bg-slate-50 rounded-2xl p-6 border border-slate-200">
                      <h3 className="font-bold text-slate-800 mb-6 text-center text-lg">Detailed P&L Statement</h3>
                      <div className="space-y-4">
                        <div className="flex justify-between items-center pb-4 border-b border-slate-200">
                          <span className="font-bold text-slate-600">Gross Rental Revenue</span>
                          <span className="text-xl font-bold text-slate-800">৳{(investment.actualEarnings / 0.55).toFixed(0)}</span>
                        </div>
                        <div className="space-y-3 py-2">
                          <div className="flex justify-between text-sm">
                            <span className="text-slate-500">Platform Management Fee (45%)</span>
                            <span className="text-red-500 font-bold">-৳{((investment.actualEarnings / 0.55) * 0.45).toFixed(0)}</span>
                          </div>
                          <div className="flex justify-between text-sm">
                            <span className="text-slate-500">Fleet Insurance & Maintenance</span>
                            <span className="text-green-600 font-bold tracking-tight uppercase text-[10px]">Included in Platform Fee</span>
                          </div>
                        </div>
                        <div className="flex justify-between items-center pt-4 border-t-2 border-slate-300">
                          <span className="text-lg font-extrabold text-slate-800">Net Return to Investor</span>
                          <span className="text-2xl font-extrabold text-green-600">৳{investment.actualEarnings.toLocaleString()}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {activeTab === 'transactions' && (
                  <div className="overflow-x-auto">
                    <table className="w-full text-left">
                      <thead className="bg-slate-50">
                        <tr>
                          <th className="px-4 py-3 text-xs font-bold text-slate-500 uppercase tracking-wider">Date</th>
                          <th className="px-4 py-3 text-xs font-bold text-slate-500 uppercase tracking-wider">Description</th>
                          <th className="px-4 py-3 text-xs font-bold text-slate-500 uppercase tracking-wider text-right">Amount</th>
                          <th className="px-4 py-3 text-xs font-bold text-slate-500 uppercase tracking-wider">Status</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-100">
                        {investmentTransactions.map(t => (
                          <tr key={t.id} className="hover:bg-slate-50 transition-colors">
                            <td className="px-4 py-4 text-sm text-slate-600 whitespace-nowrap">{t.createdAt}</td>
                            <td className="px-4 py-4">
                              <p className="text-sm font-bold text-slate-800">{t.description}</p>
                              <p className="text-xs text-slate-400">Ref: {t.id}</p>
                            </td>
                            <td className="px-4 py-4 text-sm font-extrabold text-green-600 text-right">
                              +৳{t.amount.toLocaleString()}
                            </td>
                            <td className="px-4 py-4">
                              <span className="inline-flex px-2 py-0.5 rounded text-[10px] font-bold uppercase bg-green-100 text-green-700">
                                Completed
                              </span>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            </div>
          </div>

          <div className="space-y-6">
            <div className="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm">
              <h4 className="font-bold text-slate-800 mb-4 flex items-center gap-2">
                <Zap className="w-5 h-5 text-amber-500" /> Quick Actions
              </h4>
              <div className="space-y-3">
                <button onClick={() => toast.success('Printing report...')} className="w-full px-4 py-3 border border-slate-200 text-slate-700 rounded-xl text-sm font-bold hover:bg-slate-50 flex items-center gap-3 transition-all">
                  <Printer className="w-5 h-5 text-slate-400" /> Print Summary
                </button>
                <button onClick={() => toast.success('Exporting to Excel...')} className="w-full px-4 py-3 border border-slate-200 text-slate-700 rounded-xl text-sm font-bold hover:bg-slate-50 flex items-center gap-3 transition-all">
                  <BarChart3 className="w-5 h-5 text-slate-400" /> Export Data
                </button>
                <button onClick={() => router.push('/investor/withdraw')} className="w-full px-4 py-3 bg-investor text-white rounded-xl text-sm font-bold hover:bg-investor-dark flex items-center gap-3 shadow-md shadow-investor/20 transition-all">
                  <DollarSign className="w-5 h-5" /> Withdraw Earnings
                </button>
              </div>
            </div>

            <div className="bg-blue-50 border border-blue-100 rounded-2xl p-5">
              <h4 className="font-bold text-blue-800 mb-3 flex items-center gap-2">
                <Smartphone className="w-5 h-5 text-blue-600" /> Support Desk
              </h4>
              <p className="text-xs text-blue-700 mb-4 font-medium leading-relaxed">
                Need help with this investment or bike assignment? Our team is available 24/7.
              </p>
              <button onClick={() => toast.success('Connecting to support...')} className="w-full py-2.5 bg-blue-600 text-white rounded-xl font-bold text-sm hover:bg-blue-700 transition-colors">
                Contact Support
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
