/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import { useState, useMemo } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { 
  Building2, 
  TrendingUp, 
  Users, 
  MapPin, 
  Calendar, 
  Search, 
  Bell, 
  LayoutDashboard, 
  FileText, 
  Settings,
  ChevronRight,
  ArrowUpRight,
  ArrowDownRight,
  Filter
} from 'lucide-react';
import { 
  BarChart, 
  Bar, 
  XAxis, 
  YAxis, 
  CartesianGrid, 
  Tooltip as RechartsTooltip, 
  ResponsiveContainer, 
  LineChart, 
  Line, 
  PieChart, 
  Pie, 
  Cell,
  AreaChart,
  Area
} from 'recharts';

// Mock data based on a Property Valuation context (Lonja)
const MOCK_MONTHLY_VALUATIONS = [
  { month: 'Ene', urbanas: 45, rurales: 12, total: 57 },
  { month: 'Feb', urbanas: 52, rurales: 15, total: 67 },
  { month: 'Mar', urbanas: 48, rurales: 10, total: 58 },
  { month: 'Abr', urbanas: 61, rurales: 18, total: 79 },
  { month: 'May', urbanas: 55, rurales: 20, total: 75 },
  { month: 'Jun', urbanas: 67, rurales: 25, total: 92 },
];

const MOCK_PROPERTY_TYPES = [
  { name: 'Residencial', value: 450, color: '#38bdf8' },
  { name: 'Comercial', value: 300, color: '#10b981' },
  { name: 'Rural/Fincas', value: 200, color: '#f59e0b' },
  { name: 'Industrial', value: 120, color: '#8b5cf6' },
];

const MOCK_VALUERS = [
  { id: 1, name: 'Carlos Mendoza', count: 124, rating: 4.8, status: 'Active' },
  { id: 2, name: 'Ana Rodríguez', count: 98, rating: 4.9, status: 'On Leave' },
  { id: 3, name: 'Jaime Lozano', count: 156, rating: 4.7, status: 'Active' },
  { id: 4, name: 'Elena Torres', count: 82, rating: 4.5, status: 'Active' },
];

const MOCK_RECENT_REQUESTS = [
  { id: 'VAL-2024-001', property: 'Edificio Vizcaya', type: 'Comercial', date: '2024-05-10', status: 'In Progress', value: '$450M' },
  { id: 'VAL-2024-002', property: 'Finca La Esperanza', type: 'Rural', date: '2024-05-09', status: 'Completed', value: '$820M' },
  { id: 'VAL-2024-003', property: 'Apto 402 Sol', type: 'Residencial', date: '2024-05-08', status: 'Pending', value: '$180M' },
  { id: 'VAL-2024-004', property: 'Bodega El Portal', type: 'Industrial', date: '2024-05-07', status: 'Completed', value: '$1.2B' },
];

const StatCard = ({ title, value, change, icon: Icon, color }: any) => {
  const isPositive = change > 0;
  return (
    <motion.div 
      whileHover={{ y: -5 }}
      className="bg-slate-900/50 backdrop-blur-md border border-white/10 p-6 rounded-2xl flex flex-col gap-2 relative overflow-hidden group"
    >
      <div className="absolute top-0 right-0 p-4 opacity-10 group-hover:opacity-20 transition-opacity">
        <Icon className="w-12 h-12" />
      </div>
      <div className="flex items-center gap-3 mb-2">
        <div className={`p-2 rounded-lg bg-${color}-500/10 border border-${color}-500/20`}>
          <Icon className={`w-5 h-5 text-${color}-400`} />
        </div>
        <span className="text-slate-400 text-xs font-medium uppercase tracking-wider">{title}</span>
      </div>
      <div className="flex items-end justify-between">
        <span className="text-3xl font-bold text-white tabular-nums">{value}</span>
        <div className={`flex items-center gap-0.5 text-xs font-medium ${isPositive ? 'text-emerald-400' : 'text-rose-400'}`}>
          {isPositive ? <ArrowUpRight className="w-3 h-3" /> : <ArrowDownRight className="w-3 h-3" />}
          {Math.abs(change)}%
        </div>
      </div>
    </motion.div>
  );
};

export default function App() {
  const [activeTab, setActiveTab] = useState('Overview');
  const [searchQuery, setSearchQuery] = useState('');

  const filteredRequests = useMemo(() => {
    return MOCK_RECENT_REQUESTS.filter(req => 
      req.property.toLowerCase().includes(searchQuery.toLowerCase()) ||
      req.id.toLowerCase().includes(searchQuery.toLowerCase())
    );
  }, [searchQuery]);

  return (
    <div className="min-h-screen bg-black text-slate-50 font-sans selection:bg-sky-500/30">
      {/* Sidebar - Desktop */}
      <aside className="fixed left-0 top-0 h-full w-20 md:w-64 bg-slate-900/80 backdrop-blur-xl border-r border-white/5 z-50 hidden md:flex flex-col p-6 overflow-hidden">
        <div className="flex items-center gap-3 mb-10">
          <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-sky-400 to-indigo-600 flex items-center justify-center shadow-lg shadow-sky-500/20">
            <Building2 className="w-6 h-6 text-white" />
          </div>
          <span className="text-xl font-bold tracking-tight hidden md:block">Lonja<span className="text-sky-400">Cesar</span></span>
        </div>

        <nav className="flex flex-col gap-2 flex-1">
          {[
            { name: 'Overview', icon: LayoutDashboard },
            { name: 'Properties', icon: Building2 },
            { name: 'Appraisers', icon: Users },
            { name: 'Reports', icon: FileText },
            { name: 'Settings', icon: Settings },
          ].map((item) => (
            <button
              key={item.name}
              onClick={() => setActiveTab(item.name)}
              className={`flex items-center gap-3 p-3 rounded-xl transition-all duration-200 group ${
                activeTab === item.name 
                  ? 'bg-sky-500/10 text-sky-400 border border-sky-500/20 shadow-inner' 
                  : 'text-slate-400 hover:text-white hover:bg-white/5'
              }`}
            >
              <item.icon className="w-5 h-5" />
              <span className="font-medium hidden md:block">{item.name}</span>
              {activeTab === item.name && <motion.div layoutId="activeInd" className="ml-auto w-1.5 h-1.5 rounded-full bg-sky-400 hidden md:block" />}
            </button>
          ))}
        </nav>

        <div className="mt-auto border-t border-white/5 pt-6 flex items-center gap-3">
          <div className="w-10 h-10 rounded-full bg-slate-800 border border-white/10 flex items-center justify-center overflow-hidden">
            <img src="https://api.dicebear.com/7.x/avataaars/svg?seed=Felix" alt="User" />
          </div>
          <div className="flex flex-col hidden md:block">
            <span className="text-sm font-semibold">Admin Panel</span>
            <span className="text-[10px] text-slate-500 uppercase tracking-tighter">Premium Agent</span>
          </div>
        </div>
      </aside>

      {/* Main Content */}
      <main className="md:pl-64 min-h-screen">
        {/* Header */}
        <header className="sticky top-0 z-40 bg-black/60 backdrop-blur-md border-b border-white/5 px-6 md:px-10 h-20 flex items-center justify-between">
          <div className="flex items-center gap-4 flex-1">
            <div className="relative max-w-sm w-full hidden sm:block">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-500" />
              <input 
                type="text" 
                placeholder="Search valuations, properties..." 
                className="w-full bg-slate-900/50 border border-white/10 rounded-xl py-2 pl-10 pr-4 text-sm focus:outline-none focus:ring-2 focus:ring-sky-500/40 transition-all"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
              />
            </div>
            <button className="sm:hidden p-2 bg-slate-900 border border-white/10 rounded-lg">
              <Search className="w-5 h-5 text-slate-400" />
            </button>
          </div>

          <div className="flex items-center gap-4">
            <div className="hidden sm:flex flex-col items-end mr-2 text-right">
              <span className="text-[10px] uppercase tracking-widest text-slate-500">Valledupar, Cesar</span>
              <span className="text-xs font-mono text-slate-400">{new Date().toLocaleDateString()}</span>
            </div>
            <button className="p-2.5 bg-slate-900 border border-white/10 rounded-xl relative hover:bg-slate-800 transition-colors">
              <Bell className="w-5 h-5 text-slate-400" />
              <span className="absolute top-2 right-2 w-2 h-2 bg-sky-500 rounded-full border-2 border-black"></span>
            </button>
            <button className="p-2.5 bg-slate-900 border border-white/10 rounded-xl hover:bg-slate-800 transition-colors">
              <Filter className="w-5 h-5 text-slate-400" />
            </button>
          </div>
        </header>

        {/* Content Area */}
        <div className="p-6 md:p-10 max-w-[1600px] mx-auto space-y-8">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
              <h1 className="text-3xl font-bold tracking-tight text-white mb-1">Dashboard Analytics</h1>
              <p className="text-slate-400 text-sm">Resumen de avalúos y gestión inmobiliaria en el Cesar.</p>
            </div>
            <div className="flex gap-2">
              <button className="flex items-center gap-2 bg-white text-black px-4 py-2 rounded-xl text-sm font-semibold hover:bg-slate-200 transition-colors">
                <FileText className="w-4 h-4" /> Export Excel
              </button>
              <button className="flex items-center gap-2 bg-sky-500 text-white px-4 py-2 rounded-xl text-sm font-semibold hover:bg-sky-400 transition-colors shadow-lg shadow-sky-500/20">
                New Request
              </button>
            </div>
          </div>

          {/* Stats Grid */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            <StatCard title="Total Avalúos" value="1,284" change={12.5} icon={Building2} color="sky" />
            <StatCard title="Avalúos Urbanos" value="842" change={8.2} icon={MapPin} color="emerald" />
            <StatCard title="Avalúos Rurales" value="442" change={-2.4} icon={TrendingUp} color="amber" />
            <StatCard title="Tasa Conversión" value="94.2%" change={1.5} icon={Users} color="indigo" />
          </div>

          {/* Charts Section */}
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
            {/* Main Growth Chart */}
            <div className="lg:col-span-8 bg-slate-900/30 border border-white/5 p-6 rounded-3xl backdrop-blur-md">
              <div className="flex items-center justify-between mb-8">
                <h3 className="font-semibold text-lg flex items-center gap-2">
                  <TrendingUp className="w-5 h-5 text-sky-400" /> Tendencia Mensual
                </h3>
                <div className="flex items-center gap-4">
                  <div className="flex items-center gap-2 text-xs">
                    <div className="w-3 h-3 rounded-full bg-sky-500"></div>
                    <span className="text-slate-400">Urbano</span>
                  </div>
                  <div className="flex items-center gap-2 text-xs">
                    <div className="w-3 h-3 rounded-full bg-emerald-500"></div>
                    <span className="text-slate-400">Rural</span>
                  </div>
                </div>
              </div>
              <div className="h-[350px] w-full">
                <ResponsiveContainer width="100%" height="100%">
                  <AreaChart data={MOCK_MONTHLY_VALUATIONS}>
                    <defs>
                      <linearGradient id="colorU" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor="#38bdf8" stopOpacity={0.2}/>
                        <stop offset="95%" stopColor="#38bdf8" stopOpacity={0}/>
                      </linearGradient>
                      <linearGradient id="colorR" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor="#10b981" stopOpacity={0.2}/>
                        <stop offset="95%" stopColor="#10b981" stopOpacity={0}/>
                      </linearGradient>
                    </defs>
                    <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#ffffff05" />
                    <XAxis 
                      dataKey="month" 
                      axisLine={false} 
                      tickLine={false} 
                      tick={{fill: '#64748b', fontSize: 12}} 
                      dy={10}
                    />
                    <YAxis 
                      axisLine={false} 
                      tickLine={false} 
                      tick={{fill: '#64748b', fontSize: 12}}
                    />
                    <RechartsTooltip 
                      contentStyle={{ backgroundColor: '#0f172a', border: '1px solid #ffffff10', borderRadius: '12px' }}
                      itemStyle={{ fontSize: '12px' }}
                    />
                    <Area 
                      type="monotone" 
                      dataKey="urbanas" 
                      stroke="#38bdf8" 
                      strokeWidth={3}
                      fillOpacity={1} 
                      fill="url(#colorU)" 
                    />
                    <Area 
                      type="monotone" 
                      dataKey="rurales" 
                      stroke="#10b981" 
                      strokeWidth={3}
                      fillOpacity={1} 
                      fill="url(#colorR)" 
                    />
                  </AreaChart>
                </ResponsiveContainer>
              </div>
            </div>

            {/* Property Mix */}
            <div className="lg:col-span-4 bg-slate-900/30 border border-white/5 p-6 rounded-3xl backdrop-blur-md">
              <h3 className="font-semibold text-lg mb-8 flex items-center gap-2">
                <Building2 className="w-5 h-5 text-emerald-400" /> Mix de Propiedades
              </h3>
              <div className="h-[280px] w-full">
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie
                      data={MOCK_PROPERTY_TYPES}
                      cx="50%"
                      cy="50%"
                      innerRadius={60}
                      outerRadius={80}
                      paddingAngle={5}
                      dataKey="value"
                    >
                      {MOCK_PROPERTY_TYPES.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={entry.color} />
                      ))}
                    </Pie>
                    <RechartsTooltip 
                      contentStyle={{ backgroundColor: '#0f172a', border: '1px solid #ffffff10', borderRadius: '12px' }}
                    />
                  </PieChart>
                </ResponsiveContainer>
              </div>
              <div className="mt-4 space-y-3">
                {MOCK_PROPERTY_TYPES.map((item) => (
                  <div key={item.name} className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full" style={{ backgroundColor: item.color }}></div>
                      <span className="text-sm text-slate-400">{item.name}</span>
                    </div>
                    <span className="text-sm font-semibold">{item.value}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Table Section */}
          <div className="bg-slate-900/30 border border-white/5 rounded-3xl overflow-hidden backdrop-blur-md">
            <div className="p-6 border-b border-white/5 flex items-center justify-between">
              <h3 className="font-semibold text-lg flex items-center gap-2">
                <Calendar className="w-5 h-5 text-indigo-400" /> Solicitudes Recientes
              </h3>
              <button className="text-slate-400 hover:text-white text-sm flex items-center gap-1 font-medium transition-colors">
                View All <ChevronRight className="w-4 h-4" />
              </button>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="border-b border-white/5 text-slate-500 text-[10px] uppercase tracking-wider font-semibold">
                    <th className="px-6 py-4">ID Solicitud</th>
                    <th className="px-6 py-4">Propiedad</th>
                    <th className="px-6 py-4">Tipo</th>
                    <th className="px-6 py-4">Fecha</th>
                    <th className="px-6 py-4">Valor Est.</th>
                    <th className="px-6 py-4">Estado</th>
                    <th className="px-6 py-4 text-right"></th>
                  </tr>
                </thead>
                <tbody className="text-sm">
                  <AnimatePresence>
                    {filteredRequests.map((req) => (
                      <motion.tr 
                        key={req.id}
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        className="border-b border-white/5 hover:bg-white/[0.02] group transition-colors"
                      >
                        <td className="px-6 py-5 font-mono text-sky-400/80">{req.id}</td>
                        <td className="px-6 py-5 text-white font-medium">{req.property}</td>
                        <td className="px-6 py-5 opacity-70">{req.type}</td>
                        <td className="px-6 py-5 opacity-70">{req.date}</td>
                        <td className="px-6 py-5 font-bold">{req.value}</td>
                        <td className="px-6 py-5">
                          <span className={`px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-tight ${
                            req.status === 'Completed' ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' :
                            req.status === 'In Progress' ? 'bg-sky-500/10 text-sky-400 border border-sky-500/20' :
                            'bg-slate-500/10 text-slate-400 border border-slate-500/20'
                          }`}>
                            {req.status}
                          </span>
                        </td>
                        <td className="px-6 py-5 text-right">
                          <button className="p-2 opacity-0 group-hover:opacity-100 transition-opacity hover:bg-white/10 rounded-lg">
                            <ChevronRight className="w-4 h-4" />
                          </button>
                        </td>
                      </motion.tr>
                    ))}
                  </AnimatePresence>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}

