'use client';

import { useState, useEffect } from 'react';
import { investors, bikes, transactions } from '@/data/mockData';
import { Wallet, TrendingUp, Bike, Target, DollarSign, FileText, Phone, BarChart3, Clock, ArrowRight, ShieldCheck, Zap, AlertCircle, Download, X, ExternalLink } from 'lucide-react';
import Link from 'next/link';
import TransactionList from '@/components/TransactionList';
import InvestorNotification from '@/components/InvestorNotification';

export default function InvestorDashboardPage() {
  const investor = investors[0];
  const investorBikes = bikes.filter(b => b.investorId === investor?.id);
  const recentTransactions = transactions.filter(t => t.investorId === investor.id).slice(0, 5);

  const availableBalance = investor.totalEarnings - investor.totalWithdrawn - investor.withdrawalPending;

  const [deferredPrompt, setDeferredPrompt] = useState<any>(null);
  const [showInstallBanner, setShowInstallBanner] = useState(false);

  useEffect(() => {
    const handler = (e: Event) => {
      e.preventDefault();
      setDeferredPrompt(e);
      setShowInstallBanner(true);
    };
    window.addEventListener('beforeinstallprompt', handler);
    return () => window.removeEventListener('beforeinstallprompt', handler);
  }, []);

  const handleInstall = async () => {
    if (!deferredPrompt) return;
    deferredPrompt.prompt();
    const { outcome } = await deferredPrompt.userChoice;
    if (outcome === 'accepted') {
      setDeferredPrompt(null);
    }
    setShowInstallBanner(false);
  };

  const dismissBanner = () => {
    setShowInstallBanner(false);
    localStorage.setItem('pwa_install_dismissed', 'true');
  };

  useEffect(() => {
    if (localStorage.getItem('pwa_install_dismissed') === 'true') {
      setShowInstallBanner(false);
    }
  }, []);

  return (
    <div className="min-h-screen lg:pt-6 pt-0">
      <InvestorNotification isMobile />
      <div className="pt-18 lg:pt-0 p-4 lg:p-6 max-w-8xl mx-auto mb-12 lg:mb-0">
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4 mb-6">
          <div>
            <h1 className="text-xl lg:text-2xl font-extrabold text-slate-800">Welcome back, {investor.name.split(' ')[0]} 👋</h1>
            <p className="text-sm text-slate-500">Here&apos;s what&apos;s happening with your investments today.</p>
          </div>
          <div className="flex items-center gap-2">
            {investor.kycStatus === 'verified' ? (
              <span className="inline-flex items-center gap-1 px-3 py-1.5 rounded-lg bg-green-50 border border-green-100 text-green-700 text-xs font-bold">
                <ShieldCheck className="w-4 h-4" /> KYC Verified
              </span>
            ) : (
              <Link href="/investor/profile" className="inline-flex items-center gap-1 px-3 py-1.5 rounded-lg bg-amber-50 border border-amber-200 text-amber-700 text-xs font-bold hover:bg-amber-100 transition-colors">
                <AlertCircle className="w-4 h-4" /> Complete KYC
              </Link>
            )}
            {/* <Link href="/investor/plans" className="px-4 py-2 bg-investor text-white rounded-lg text-sm font-bold hover:bg-investor-dark transition-colors flex items-center gap-2 shadow-sm shadow-investor/20">
              <Zap className="w-4 h-4" /> New Investment
            </Link> */}
          </div>
        </div>

        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
          <div className="bg-white rounded-2xl p-5 border border-slate-200 shadow-sm relative overflow-hidden group hover:border-investor/30 transition-all">
            <div className="absolute -right-4 -top-4 w-16 h-16 bg-purple-50 rounded-full group-hover:scale-150 transition-transform duration-500"></div>
            <div className="flex items-center gap-3 mb-2 relative z-10">
              <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">Total Invested</p>
            </div>
            <p className="text-2xl font-extrabold text-slate-800 relative z-10">৳{(investor.totalInvested / 1000).toFixed(0)}k</p>
          </div>

          <div className="bg-white rounded-2xl p-5 border border-slate-200 shadow-sm relative overflow-hidden group hover:border-green-500/30 transition-all">
            <div className="absolute -right-4 -top-4 w-16 h-16 bg-green-50 rounded-full group-hover:scale-150 transition-transform duration-500"></div>
            <div className="flex items-center gap-3 mb-2 relative z-10">
              <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 Earnings</p>
            </div>
            <p className="text-2xl font-extrabold text-green-600 relative z-10">৳{(investor.totalEarnings / 1000).toFixed(1)}k</p>
          </div>

          <div className="bg-white rounded-2xl p-5 border border-slate-200 shadow-sm relative overflow-hidden group hover:border-amber-500/30 transition-all">
            <div className="absolute -right-4 -top-4 w-16 h-16 bg-amber-50 rounded-full group-hover:scale-150 transition-transform duration-500"></div>
            <div className="flex items-center gap-3 mb-2 relative z-10">
              <div className="w-10 h-10 bg-amber-100 rounded-xl flex items-center justify-center">
                <Bike className="w-5 h-5 text-amber-600" />
              </div>
              <p className="text-sm text-slate-500 font-medium">Active Bikes</p>
            </div>
            <p className="text-2xl font-extrabold text-amber-600 relative z-10">{investor.activeBikes}</p>
          </div>

          <div className="bg-white rounded-2xl p-5 border border-slate-200 shadow-sm relative overflow-hidden group hover:border-blue-500/30 transition-all">
            <div className="absolute -right-4 -top-4 w-16 h-16 bg-blue-50 rounded-full group-hover:scale-150 transition-transform duration-500"></div>
            <div className="flex items-center gap-3 mb-2 relative z-10">
              <div className="w-10 h-10 bg-blue-100 rounded-xl flex items-center justify-center">
                <Target className="w-5 h-5 text-blue-600" />
              </div>
              <p className="text-sm text-slate-500 font-medium">Avg. ROI</p>
            </div>
            <p className="text-2xl font-extrabold text-blue-600 relative z-10">{investor.roi}%</p>
          </div>
        </div>

        {/* PWA Install Banner */}
        {showInstallBanner && (
          <div className="bg-gradient-to-r from-investor/10 to-purple-50 border border-investor/20 rounded-2xl p-4 mb-6 animate-in fade-in slide-in-from-bottom-4">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 bg-gradient-to-br from-investor to-investor-light rounded-xl flex items-center justify-center shrink-0 shadow-lg">
                <Download className="w-6 h-6 text-white" />
              </div>
              <div className="flex-1 min-w-0">
                <p className="font-bold text-slate-800">Install JML Investor App</p>
                <p className="text-xs text-slate-500 mt-0.5">Add to home screen for quick access & offline support</p>
              </div>
              <div className="flex items-center gap-2 shrink-0">
                <button onClick={dismissBanner} className="p-2 hover:bg-slate-100 rounded-lg text-slate-400 transition-colors">
                  <X className="w-5 h-5" />
                </button>
                <button onClick={handleInstall} className="px-4 py-2 bg-investor text-white rounded-lg font-bold text-sm hover:bg-investor-dark transition-colors flex items-center gap-2 shadow-sm">
                  <ExternalLink className="w-4 h-4" /> Install
                </button>
              </div>
            </div>
          </div>
        )}

        <div className="grid lg:grid-cols-3 gap-6 mb-6">
          <div className="lg:col-span-2 bg-white rounded-2xl border border-slate-200 shadow-sm flex flex-col">
            <div className="p-5 border-b border-slate-100 flex items-center justify-between">
              <h2 className="font-bold text-slate-800 flex items-center gap-2">
                <Bike className="w-5 h-5 text-slate-400" /> My Portfolio Overview
              </h2>
              <Link href="/investor/plans" className="text-sm font-semibold text-investor hover:text-investor-dark flex items-center gap-1">
                View All <ArrowRight className="w-4 h-4" />
              </Link>
            </div>
            <div className="p-5 flex-1">
              {investorBikes.length > 0 ? (
                <div className="space-y-4">
                  {investorBikes.slice(0, 3).map(bike => (
                    <Link
                      key={bike.id}
                      href={`/investor/investments/${investor.investments?.[0].id || 'ip1'}`}
                      className="flex items-center gap-4 p-3 hover:bg-slate-50 rounded-xl transition-colors border border-transparent hover:border-slate-100 group"
                    >
                      <div className="w-12 h-12 bg-slate-100 rounded-lg overflow-hidden shrink-0">
                        <img src={bike.image} alt={bike.model} className="w-full h-full object-cover" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <h4 className="font-bold text-slate-800 truncate group-hover:text-investor transition-colors">{bike.model}</h4>
                        <p className="text-xs text-slate-500">{bike.plateNumber}</p>
                      </div>
                      <div className="text-right">
                        <p className="font-bold text-green-600">৳{bike.currentRent || 0}</p>
                        <p className="text-[10px] text-slate-400 uppercase">Daily Rent</p>
                      </div>
                      <div>
                        <span className={`inline-flex px-2 py-1 rounded text-[10px] font-bold uppercase ${bike.status === 'rented' ? 'bg-green-100 text-green-700' :
                          bike.status === 'available' ? 'bg-blue-100 text-blue-700' : 'bg-amber-100 text-amber-700'
                          }`}>
                          {bike.status}
                        </span>
                      </div>
                    </Link>
                  ))}
                </div>
              ) : (
                <div className="h-full flex flex-col items-center justify-center text-center py-8">
                  <div className="w-12 h-12 bg-slate-50 rounded-full flex items-center justify-center mb-3">
                    <Bike className="w-6 h-6 text-slate-300" />
                  </div>
                  <p className="text-sm font-semibold text-slate-700">No bikes assigned yet</p>
                  <p className="text-xs text-slate-500 mt-1 max-w-[200px]">Once you make an investment, assigned bikes will appear here.</p>
                </div>
              )}
            </div>
          </div>

          <div className="bg-white rounded-2xl border border-slate-200 shadow-sm flex flex-col">
            <div className="p-5 border-b border-slate-100">
              <h2 className="font-bold text-slate-800">Quick Actions</h2>
            </div>
            <div className="p-5 flex-1 flex flex-col gap-3">
              <div className="bg-investor/5 border border-investor/10 rounded-xl p-4 mb-2">
                <p className="text-xs text-investor font-semibold mb-1 uppercase">Available to Withdraw</p>
                <p className="text-2xl font-extrabold text-investor mb-3">৳{availableBalance.toLocaleString()}</p>
                <Link href="/investor/withdraw" className="w-full py-2.5 bg-investor text-white rounded-lg font-bold text-sm hover:bg-investor-dark flex items-center justify-center gap-2 shadow-sm shadow-investor/20 transition-all">
                  <DollarSign className="w-4 h-4" /> Withdraw Funds
                </Link>
              </div>

              <Link href="/investor/profile" className="flex items-center gap-3 p-3 border border-slate-100 rounded-xl hover:bg-slate-50 transition-colors group">
                <div className="w-10 h-10 bg-slate-100 rounded-lg flex items-center justify-center group-hover:bg-white group-hover:shadow-sm transition-all">
                  <FileText className="w-5 h-5 text-slate-500 group-hover:text-investor" />
                </div>
                <div className="flex-1">
                  <p className="font-semibold text-sm text-slate-800">Update KYC</p>
                  <p className="text-xs text-slate-500">Manage documents</p>
                </div>
              </Link>

              <Link href="/investor/plans" className="flex items-center gap-3 p-3 border border-slate-100 rounded-xl hover:bg-slate-50 transition-colors group">
                <div className="w-10 h-10 bg-slate-100 rounded-lg flex items-center justify-center group-hover:bg-white group-hover:shadow-sm transition-all">
                  <BarChart3 className="w-5 h-5 text-slate-500 group-hover:text-investor" />
                </div>
                <div className="flex-1">
                  <p className="font-semibold text-sm text-slate-800">Earnings & P&L</p>
                  <p className="text-xs text-slate-500">View detailed reports</p>
                </div>
              </Link>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-2xl border border-slate-200 shadow-sm">
          <div className="p-5 border-b border-slate-100 flex items-center justify-between">
            <h2 className="font-bold text-slate-800 flex items-center gap-2">
              <Clock className="w-5 h-5 text-slate-400" /> Recent Transactions
            </h2>
            <button className="text-sm font-semibold text-investor hover:text-investor-dark flex items-center gap-1">
              View All <ArrowRight className="w-4 h-4" />
            </button>
          </div>
          <div className="p-0">
            <TransactionList transactions={recentTransactions} />
          </div>
        </div>
      </div>
    </div>
  );
}