import React, { useEffect, useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import {
  ArrowLeft, Users, Briefcase, Buildings, TrendUp, EnvelopeSimple,
  Phone, Globe, MapPin, ChartLineUp, CurrencyDollar, UserPlus,
  ChartPieSlice, ArrowUp, ArrowDown, Star, IdentificationBadge,
  CalendarBlank, CheckCircle, X, Eye, Receipt, Wallet
} from '@phosphor-icons/react';
import {
  AreaChart, Area, BarChart, Bar, PieChart, Pie, Cell,
  XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend
} from 'recharts';
import axios from 'axios';
import toast from 'react-hot-toast';

const BRAND = '#5D4037';
const COLORS = ['#5D4037','#6D4C41','#A1887F','#C6A862','#10b981','#f59e0b','#ec4899','#06b6d4'];

export default function CompanyDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [company, setCompany] = useState(null);
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchCompanyDetails();
    fetchCompanyStats();
  }, [id]);

  const fetchCompanyDetails = async () => {
    try {
      const response = await axios.get(`/api/companies/${id}`);
      setCompany(response.data);
    } catch (error) {
      toast.error('Failed to fetch company details');
      navigate('/companies');
    } finally {
      setLoading(false);
    }
  };

  const fetchCompanyStats = async () => {
    try {
      const response = await axios.get(`/api/companies/${id}/statistics`);
      setStats(response.data);
    } catch (error) {
      console.error('Failed to fetch stats:', error);
    }
  };

  // Build chart data from stats
  const hireData = (stats?.monthly_hire_trend || []).map(d => ({ month: d.month, hires: d.count }));

  const deptData = (stats?.employees_by_department || []).map(d => ({
    name: d.department?.length > 14 ? d.department.slice(0,14)+'…' : d.department,
    count: d.count,
  }));

  const empTypeData = [
    { name:'Full Time', value: stats?.employment_types?.full_time || 0 },
    { name:'Part Time',  value: stats?.employment_types?.part_time  || 0 },
    { name:'Contract',   value: stats?.employment_types?.contract   || 0 },
  ].filter(d => d.value > 0);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="flex flex-col items-center gap-4">
          <div className="animate-spin rounded-full h-14 w-14 border-4 border-t-transparent" style={{ borderColor: `${BRAND}40`, borderTopColor: BRAND }}></div>
          <p className="text-sm text-gray-500 font-medium">Loading company data…</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6 fade-in">
      {/* Back */}
      <button onClick={() => navigate('/companies')}
        className="flex items-center gap-2 text-sm font-semibold text-gray-500 hover:text-gray-900 transition-colors group">
        <ArrowLeft size={18} weight="bold" className="group-hover:-translate-x-0.5 transition-transform" />
        Back to Companies
      </button>

      {/* Hero Banner */}
      <div className="rounded-2xl overflow-hidden shadow-xl" style={{ background:'linear-gradient(135deg,#3E2723 0%,#5D4037 60%,#6D4C41 100%)' }}>
        <div className="p-8 flex flex-col md:flex-row items-start md:items-center justify-between gap-6">
          <div className="flex items-center gap-5">
            <div className="w-20 h-20 rounded-2xl glass-dark flex items-center justify-center text-white font-extrabold text-3xl shadow-2xl border border-white/20">
              {company?.name?.charAt(0)}
            </div>
            <div>
              <div className="flex items-center gap-3 mb-1">
                <h1 className="text-3xl font-extrabold text-white">{company?.name}</h1>
                <span className={`px-2.5 py-0.5 rounded-full text-xs font-bold capitalize ${company?.status==='active' ? 'bg-green-400/20 text-green-300 border border-green-400/30' : 'bg-gray-400/20 text-gray-300'}`}>
                  {company?.status}
                </span>
              </div>
              <p className="text-primary-200 font-medium">{company?.industry || 'General Business'}</p>
              <p className="text-primary-300 text-sm mt-1 max-w-xl">{company?.description}</p>
            </div>
          </div>
          {/* Contact strip */}
          <div className="flex flex-wrap gap-3">
            {company?.email && (
              <a href={`mailto:${company.email}`} className="flex items-center gap-2 px-3 py-2 rounded-xl glass-dark text-primary-200 text-sm hover:text-white transition-colors">
                <EnvelopeSimple size={16} weight="duotone" /> {company.email}
              </a>
            )}
            {company?.website && (
              <a href={company.website} target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 px-3 py-2 rounded-xl glass-dark text-primary-200 text-sm hover:text-white transition-colors">
                <Globe size={16} weight="duotone" /> Website
              </a>
            )}
          </div>
        </div>
        {/* Stats strip */}
        <div className="grid grid-cols-2 md:grid-cols-4 border-t border-white/10">
          {[
            { label:'Employees', value: stats?.total_employees || 0, icon: Users },
            { label:'Departments', value: stats?.total_departments || 0, icon: Briefcase },
            { label:'Active Staff', value: stats?.active_employees || 0, icon: CheckCircle },
            { label:'System Users', value: stats?.total_users || 0, icon: IdentificationBadge },
          ].map((s,i) => (
            <div key={i} className={`flex items-center gap-4 px-6 py-4 ${i < 3 ? 'border-r border-white/10' : ''}`}>
              <div className="w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center">
                <s.icon size={20} weight="duotone" className="text-white" />
              </div>
              <div>
                <p className="text-2xl font-extrabold text-white">{s.value}</p>
                <p className="text-xs text-primary-300">{s.label}</p>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Financial KPIs */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {[
          { label: 'Income / Revenue', value: `₦${(stats?.financial?.revenue || 0).toLocaleString()}`, icon: CurrencyDollar, color: '#5D4037', bg: '#EFEBE9' },
          { label: 'Expenses', value: `₦${(stats?.financial?.expenses || 0).toLocaleString()}`, icon: Receipt, color: '#ef4444', bg: '#fee2e2' },
          { label: 'Net Profit', value: `₦${(stats?.financial?.net_profit || 0).toLocaleString()}`, icon: TrendUp, color: '#10b981', bg: '#dcfce7' },
          { label: 'Money in Bank', value: `₦${(stats?.financial?.cash_balance || 0).toLocaleString()}`, icon: Wallet, color: '#f59e0b', bg: '#fef3c7' },
          { label: 'Total Assets', value: `₦${(stats?.financial?.total_assets || 0).toLocaleString()}`, icon: Buildings, color: '#8b5cf6', bg: '#ede9fe' },
          { label: 'Credit Score', value: stats?.financial?.credit_score || '—', icon: Star, color: '#ec4899', bg: '#fce7f3' },
          { label: 'Runway (Days)', value: stats?.financial?.runway_days || '—', icon: CalendarBlank, color: '#06b6d4', bg: '#cffafe' },
          { label: 'Profit Margin', value: `${stats?.financial?.profit_margin || 0}%`, icon: ChartLineUp, color: '#14b8a6', bg: '#ccfbf1' },
        ].map((kpi, i) => (
          <div key={i} className="bg-white rounded-xl shadow-sm border border-gray-100 p-4 hover:shadow-md transition-all">
            <div className="flex items-center justify-between mb-2">
              <span className="text-xs font-medium text-gray-500">{kpi.label}</span>
              <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{ background: kpi.bg }}>
                <kpi.icon size={16} weight="duotone" style={{ color: kpi.color }} />
              </div>
            </div>
            <p className="text-lg font-bold text-gray-900">{kpi.value}</p>
          </div>
        ))}
      </div>

      {/* Revenue vs Expenses + Expense Breakdown */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-5">
            <h3 className="font-bold text-gray-900 flex items-center gap-2">
              <ChartLineUp size={20} weight="duotone" style={{ color: BRAND }} /> Revenue vs Expenses — 6 Months
            </h3>
          </div>
          {(stats?.revenue_trend || []).length > 0 ? (
            <ResponsiveContainer width="100%" height={220}>
              <AreaChart data={stats.revenue_trend}>
                <defs>
                  <linearGradient id="revGrad" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%"  stopColor={BRAND}     stopOpacity={0.25} />
                    <stop offset="95%" stopColor={BRAND}     stopOpacity={0} />
                  </linearGradient>
                  <linearGradient id="expGrad" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%"  stopColor="#dc2626" stopOpacity={0.15} />
                    <stop offset="95%" stopColor="#dc2626" stopOpacity={0} />
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                <XAxis dataKey="month" style={{ fontSize:12 }} stroke="#9ca3af" />
                <YAxis style={{ fontSize:12 }} stroke="#9ca3af" tickFormatter={v=>`₦${(v/1000).toFixed(0)}K`} />
                <Tooltip formatter={v=>`₦${Number(v).toLocaleString()}`} contentStyle={{ borderRadius:'12px', fontSize:12 }} />
                <Area type="monotone" dataKey="revenue"  name="Revenue"  stroke={BRAND}     strokeWidth={2.5} fill="url(#revGrad)" />
                <Area type="monotone" dataKey="expenses" name="Expenses" stroke="#dc2626"   strokeWidth={2}   fill="url(#expGrad)" />
              </AreaChart>
            </ResponsiveContainer>
          ) : (
            <div className="h-[220px] flex items-center justify-center text-gray-400 text-sm">No financial trend data yet</div>
          )}
        </div>

        {/* Expense Breakdown Pie */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          <h3 className="font-bold text-gray-900 mb-5 flex items-center gap-2">
            <ChartPieSlice size={20} weight="duotone" style={{ color: BRAND }} /> Expense Breakdown
          </h3>
          {(stats?.expense_breakdown || []).length > 0 ? (
            <>
              <ResponsiveContainer width="100%" height={160}>
                <PieChart>
                  <Pie data={stats.expense_breakdown} cx="50%" cy="50%" innerRadius={45} outerRadius={70} paddingAngle={3} dataKey="value">
                    {stats.expense_breakdown.map((d,i) => <Cell key={i} fill={d.color || COLORS[i % COLORS.length]} />)}
                  </Pie>
                  <Tooltip formatter={v=>`₦${Number(v).toLocaleString()}`} contentStyle={{ borderRadius:'10px', fontSize:12 }} />
                </PieChart>
              </ResponsiveContainer>
              <div className="space-y-1 mt-2">
                {stats.expense_breakdown.slice(0,5).map((d,i) => (
                  <div key={i} className="flex items-center justify-between text-xs">
                    <div className="flex items-center gap-2">
                      <div className="w-2.5 h-2.5 rounded-full" style={{ background: d.color || COLORS[i % COLORS.length] }} />
                      <span className="text-gray-600">{d.name}</span>
                    </div>
                    <span className="font-bold text-gray-900">₦{Number(d.value).toLocaleString()}</span>
                  </div>
                ))}
              </div>
            </>
          ) : (
            <div className="h-[160px] flex items-center justify-center text-gray-400 text-sm">No expense categories yet</div>
          )}
        </div>
      </div>

      {/* Charts Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Hiring trend */}
        <div className="lg:col-span-2 bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-5">
            <h3 className="font-bold text-gray-900 flex items-center gap-2">
              <TrendUp size={20} weight="duotone" style={{ color: BRAND }} /> Hiring Trend
            </h3>
            <span className="text-xs font-semibold px-3 py-1 rounded-full" style={{ background:'#e8e8fd', color: BRAND }}>6 months</span>
          </div>
          {hireData.length > 0 ? (
            <ResponsiveContainer width="100%" height={220}>
              <AreaChart data={hireData}>
                <defs>
                  <linearGradient id="hGrad" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%"  stopColor={BRAND} stopOpacity={0.25} />
                    <stop offset="95%" stopColor={BRAND} stopOpacity={0} />
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                <XAxis dataKey="month" style={{ fontSize:12 }} stroke="#9ca3af" />
                <YAxis style={{ fontSize:12 }} stroke="#9ca3af" allowDecimals={false} />
                <Tooltip contentStyle={{ borderRadius:'12px', fontSize:12 }} />
                <Area type="monotone" dataKey="hires" name="New Hires" stroke={BRAND} strokeWidth={2.5} fill="url(#hGrad)" />
              </AreaChart>
            </ResponsiveContainer>
          ) : (
            <div className="h-[220px] flex items-center justify-center text-gray-400 text-sm">No hire data available</div>
          )}
        </div>

        {/* Employment Types Pie */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          <h3 className="font-bold text-gray-900 mb-5 flex items-center gap-2">
            <ChartPieSlice size={20} weight="duotone" style={{ color: BRAND }} /> Employment Types
          </h3>
          {empTypeData.length > 0 ? (
            <>
              <ResponsiveContainer width="100%" height={180}>
                <PieChart>
                  <Pie data={empTypeData} cx="50%" cy="50%" innerRadius={50} outerRadius={75} paddingAngle={3} dataKey="value">
                    {empTypeData.map((_,i)=><Cell key={i} fill={COLORS[i]} />)}
                  </Pie>
                  <Tooltip contentStyle={{ borderRadius:'10px', fontSize:12 }} />
                </PieChart>
              </ResponsiveContainer>
              <div className="space-y-2 mt-2">
                {empTypeData.map((d,i)=>(
                  <div key={i} className="flex items-center justify-between text-sm">
                    <div className="flex items-center gap-2">
                      <div className="w-2.5 h-2.5 rounded-full" style={{ background: COLORS[i] }} />
                      <span className="text-gray-600">{d.name}</span>
                    </div>
                    <span className="font-bold text-gray-900">{d.value}</span>
                  </div>
                ))}
              </div>
            </>
          ) : (
            <div className="h-[180px] flex items-center justify-center text-gray-400 text-sm">No data</div>
          )}
        </div>
      </div>

      {/* Dept Bar Chart + Info */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          <h3 className="font-bold text-gray-900 mb-5 flex items-center gap-2">
            <Briefcase size={20} weight="duotone" style={{ color: BRAND }} /> Headcount by Department
          </h3>
          {deptData.length > 0 ? (
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={deptData} layout="vertical">
                <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" horizontal={false} />
                <XAxis type="number" style={{ fontSize:11 }} stroke="#9ca3af" allowDecimals={false} />
                <YAxis type="category" dataKey="name" style={{ fontSize:11 }} stroke="#9ca3af" width={100} />
                <Tooltip contentStyle={{ borderRadius:'10px', fontSize:12 }} />
                <Bar dataKey="count" name="Employees" radius={[0,6,6,0]}>
                  {deptData.map((_,i)=><Cell key={i} fill={COLORS[i % COLORS.length]} />)}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          ) : (
            <div className="h-[220px] flex items-center justify-center text-gray-400 text-sm">No department data</div>
          )}
        </div>

        {/* Company Info Card */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 space-y-4">
          <h3 className="font-bold text-gray-900 mb-4 flex items-center gap-2">
            <Buildings size={20} weight="duotone" style={{ color: BRAND }} /> Company Info
          </h3>
          {[
            { icon: EnvelopeSimple, label:'Email',   val: company?.email },
            { icon: Phone,          label:'Phone',   val: company?.phone },
            { icon: Globe,          label:'Website', val: company?.website },
            { icon: MapPin,         label:'Address', val: company?.address },
            { icon: CalendarBlank,  label:'Founded', val: company?.created_at ? new Date(company.created_at).getFullYear() : null },
          ].filter(r=>r.val).map((r,i) => (
            <div key={i} className="flex items-start gap-3 p-3 rounded-xl" style={{ background:'#f8f9ff' }}>
              <div className="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0" style={{ background:'#e8e8fd' }}>
                <r.icon size={16} weight="duotone" style={{ color: BRAND }} />
              </div>
              <div className="min-w-0">
                <p className="text-xs text-gray-400 font-semibold uppercase tracking-wider">{r.label}</p>
                <p className="text-sm text-gray-800 font-medium truncate">{r.val}</p>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Company Users & Roles */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100">
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
          <h3 className="font-bold text-gray-900 flex items-center gap-2">
            <IdentificationBadge size={20} weight="duotone" style={{ color: BRAND }} /> Company Users & Roles
          </h3>
          <Link to={`/company-users?company_id=${id}`} className="flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs font-semibold text-white" style={{ background: BRAND }}>
            <UserPlus size={14} weight="bold" /> Manage Users
          </Link>
        </div>
        <div className="px-6 py-4">
          <p className="text-sm text-gray-600">Create and manage login accounts for this company. Assign roles like <strong>Company Admin</strong> (manager) or <strong>Company User</strong>. Each user only sees data for this company.</p>
          <div className="mt-3 flex flex-wrap gap-2">
            <Link to={`/company-users?company_id=${id}`} className="flex items-center gap-2 px-4 py-2 rounded-xl border text-sm font-medium hover:shadow-sm transition-all" style={{ borderColor: BRAND, color: BRAND }}>
              <Users size={16} /> View Users
            </Link>
            <Link to={`/company-users?company_id=${id}&action=create`} className="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium text-white hover:opacity-90 transition-all" style={{ background: BRAND }}>
              <UserPlus size={16} /> Add User
            </Link>
          </div>
        </div>
      </div>

      {/* Employee Table */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100">
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
          <h3 className="font-bold text-gray-900 flex items-center gap-2">
            <Users size={20} weight="duotone" style={{ color: BRAND }} /> Employees
          </h3>
          <span className="text-xs font-semibold px-3 py-1 rounded-full" style={{ background:'#e8e8fd', color: BRAND }}>
            {stats?.total_employees || 0} total
          </span>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full data-table">
            <thead>
              <tr>
                <th>Employee</th>
                <th>Department</th>
                <th>Position</th>
                <th>Type</th>
                <th>Hired</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {(stats?.recent_hires || []).slice(0,10).map(emp => (
                <tr key={emp.id}>
                  <td>
                    <div className="flex items-center gap-3">
                      <div className="w-8 h-8 rounded-full flex items-center justify-center text-white font-bold text-xs flex-shrink-0"
                        style={{ background:'linear-gradient(135deg,#5D4037,#6D4C41)' }}>
                        {emp.first_name?.[0]}{emp.last_name?.[0]}
                      </div>
                      <div>
                        <p className="font-semibold text-gray-900 text-sm">{emp.full_name}</p>
                        <p className="text-xs text-gray-400">{emp.email}</p>
                      </div>
                    </div>
                  </td>
                  <td className="text-gray-600">{emp.department?.name || '—'}</td>
                  <td className="text-gray-600">{emp.position}</td>
                  <td>
                    <span className="px-2 py-0.5 rounded-md text-xs font-semibold capitalize" style={{ background:'#EFEBE9', color:'#5D4037' }}>
                      {emp.employment_type?.replace('_',' ') || '—'}
                    </span>
                  </td>
                  <td className="text-gray-500 text-xs">{emp.hire_date ? new Date(emp.hire_date).toLocaleDateString() : '—'}</td>
                  <td>
                    <span className={`px-2 py-0.5 rounded-md text-xs font-bold capitalize ${emp.status==='active' ? 'bg-green-50 text-green-700' : 'bg-gray-50 text-gray-500'}`}>
                      {emp.status}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {(!stats?.recent_hires || stats.recent_hires.length === 0) && (
            <div className="py-16 text-center text-gray-400">
              <Users size={40} weight="duotone" className="mx-auto mb-2 opacity-40" />
              <p className="text-sm">No employee records found</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
