import { useState, useEffect } from 'react';
import api from '../lib/api';
import {
  CreditCard,
  Users,
  Shield,
  CheckCircle2,
  AlertTriangle,
  Download,
  Trash2,
  UserPlus,
  Building2,
  Activity,
} from 'lucide-react';
import { motion } from 'framer-motion';

interface PlanDefinition {
  id: 'trial' | 'solo' | 'team' | 'scale';
  name: string;
  monthlyPriceUsd: number;
  annualMonthlyPriceUsd: number;
  includedMinutes: number;
  maxCompanies: number;
  maxSeats: number;
  overageRatePerMinUsd: number;
  features: string[];
}

interface UsageResponse {
  tenantName: string;
  currentPlan: PlanDefinition;
  usage: {
    totalCalls: number;
    totalDurationSeconds: number;
    usedMinutes: number;
    includedMinutes: number;
    remainingMinutes: number;
    overageMinutes: number;
    overageCostUsd: number;
    utilizationPercent: number;
    companyCount: number;
    maxCompanies: number;
    seatCount: number;
    maxSeats: number;
    limitWarning: boolean;
    limitExceeded: boolean;
  };
  stripeConfigured: boolean;
}

interface TeamMember {
  _id: string;
  name: string;
  email: string;
  role: string;
  tenantName: string;
  createdAt: string;
}

interface AuditLogEntry {
  _id: string;
  actorEmail: string;
  actorRole: string;
  action: string;
  resourceType: string;
  resourceId?: string;
  createdAt: string;
}

interface AdminOverview {
  totalTenants: number;
  totalUsers: number;
  totalCompanies: number;
  totalCalls: number;
  estimatedMrrUsd: number;
  tenants: Array<{
    tenantName: string;
    plan: string;
    usersCount: number;
    companiesCount: number;
    callsCount: number;
    minutesUsed: number;
    monthlyRevenueUsd: number;
  }>;
}

const Billing = () => {
  const [plans, setPlans] = useState<PlanDefinition[]>([]);
  const [usageData, setUsageData] = useState<UsageResponse | null>(null);
  const [team, setTeam] = useState<TeamMember[]>([]);
  const [auditLogs, setAuditLogs] = useState<AuditLogEntry[]>([]);
  const [adminOverview, setAdminOverview] = useState<AdminOverview | null>(null);

  const [billingInterval, setBillingInterval] = useState<'monthly' | 'annual'>('annual');
  const [couponCode, setCouponCode] = useState('');
  const [statusMessage, setStatusMessage] = useState('');

  // Invite form state
  const [inviteName, setInviteName] = useState('');
  const [inviteEmail, setInviteEmail] = useState('');
  const [inviteRole, setInviteRole] = useState<'admin' | 'member'>('member');
  const [inviting, setInviting] = useState(false);

  const reloadAll = async () => {
    try {
      const [plansRes, usageRes, teamRes, logsRes] = await Promise.all([
        api.get<PlanDefinition[]>('/billing/plans'),
        api.get<UsageResponse>('/billing/usage'),
        api.get<TeamMember[]>('/billing/team'),
        api.get<AuditLogEntry[]>('/privacy/audit-logs'),
      ]);
      setPlans(plansRes.data);
      setUsageData(usageRes.data);
      setTeam(teamRes.data);
      setAuditLogs(logsRes.data);

      api
        .get<AdminOverview>('/billing/admin-overview')
        .then((res) => setAdminOverview(res.data))
        .catch(() => {});
    } catch (err) {
      console.error('Failed to load billing & workspace data', err);
    }
  };

  useEffect(() => {
    let active = true;
    Promise.all([
      api.get<PlanDefinition[]>('/billing/plans'),
      api.get<UsageResponse>('/billing/usage'),
      api.get<TeamMember[]>('/billing/team'),
      api.get<AuditLogEntry[]>('/privacy/audit-logs'),
    ])
      .then(([plansRes, usageRes, teamRes, logsRes]) => {
        if (!active) return;
        setPlans(plansRes.data);
        setUsageData(usageRes.data);
        setTeam(teamRes.data);
        setAuditLogs(logsRes.data);
      })
      .catch((err) => console.error('Failed to load billing data', err));

    api
      .get<AdminOverview>('/billing/admin-overview')
      .then((res) => {
        if (active) setAdminOverview(res.data);
      })
      .catch(() => {});

    return () => {
      active = false;
    };
  }, []);

  const handleSelectPlan = async (planId: PlanDefinition['id']) => {
    setStatusMessage('');
    try {
      const res = await api.post<{ message: string; checkoutUrl?: string }>(
        '/billing/change-plan',
        {
          planId,
          billingInterval,
          couponCode: couponCode.trim() || undefined,
        }
      );
      if (res.data.checkoutUrl) {
        window.location.assign(res.data.checkoutUrl);
        return;
      }
      setStatusMessage(res.data.message);
      reloadAll();
    } catch (err: unknown) {
      const apiErr = err as { response?: { data?: { error?: string } } };
      setStatusMessage(apiErr?.response?.data?.error || 'Failed to switch subscription plan.');
    }
  };

  const handleInviteMember = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!inviteName.trim() || !inviteEmail.trim()) return;
    setInviting(true);
    setStatusMessage('');
    try {
      await api.post('/billing/team/invite', {
        name: inviteName.trim(),
        email: inviteEmail.trim(),
        role: inviteRole,
      });
      setInviteName('');
      setInviteEmail('');
      setStatusMessage('Team member invited to workspace successfully!');
      reloadAll();
    } catch (err: unknown) {
      const apiErr = err as { response?: { data?: { error?: string } } };
      setStatusMessage(apiErr?.response?.data?.error || 'Failed to invite team member.');
    } finally {
      setInviting(false);
    }
  };

  const handleRemoveMember = async (userId: string) => {
    if (!confirm('Remove this team member from the workspace?')) return;
    try {
      await api.delete(`/billing/team/${userId}`);
      reloadAll();
    } catch (err: unknown) {
      const apiErr = err as { response?: { data?: { error?: string } } };
      setStatusMessage(apiErr?.response?.data?.error || 'Failed to remove team member.');
    }
  };

  const handleGdprExport = async () => {
    try {
      const res = await api.get('/privacy/export');
      const blob = new Blob([JSON.stringify(res.data, null, 2)], {
        type: 'application/json;charset=utf-8;',
      });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `gdpr-workspace-export-${new Date().toISOString().slice(0, 10)}.json`;
      link.click();
      URL.revokeObjectURL(url);
      setStatusMessage('GDPR Article 20 JSON Data Export downloaded.');
      reloadAll();
    } catch {
      setStatusMessage('Failed to export GDPR workspace data.');
    }
  };

  const handleGdprEraseCalls = async () => {
    if (
      !confirm(
        'GDPR Right to Erasure: Are you sure you want to permanently delete ALL call logs and conversation transcripts for this tenant?'
      )
    ) {
      return;
    }
    try {
      const res = await api.delete<{ message: string }>('/privacy/erase-calls');
      setStatusMessage(res.data.message);
      reloadAll();
    } catch {
      setStatusMessage('Failed to erase call history.');
    }
  };

  return (
    <div className="space-y-10 pb-16">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white tracking-tight flex items-center gap-2.5">
            <CreditCard className="w-6 h-6 text-indigo-400" />
            SaaS Billing, Usage Metering, Team & GDPR Compliance
          </h1>
          <p className="text-sm text-slate-400 mt-1">
            Manage your subscription tier, per-minute AI voice allowance, team RBAC seats, and GDPR data controls.
          </p>
        </div>

        {/* Monthly / Annual Toggle */}
        <div className="flex items-center gap-2 bg-slate-900 border border-white/10 p-1 rounded-xl">
          <button
            onClick={() => setBillingInterval('monthly')}
            className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
              billingInterval === 'monthly'
                ? 'bg-indigo-600 text-white'
                : 'text-slate-400 hover:text-white'
            }`}
          >
            Monthly Billing
          </button>
          <button
            onClick={() => setBillingInterval('annual')}
            className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
              billingInterval === 'annual'
                ? 'bg-indigo-600 text-white'
                : 'text-slate-400 hover:text-white'
            }`}
          >
            Annual (Save 20%)
          </button>
        </div>
      </div>

      {statusMessage && (
        <div className="p-4 rounded-xl bg-indigo-500/10 border border-indigo-500/30 text-indigo-200 text-sm font-medium">
          {statusMessage}
        </div>
      )}

      {/* Live Usage Metering Card */}
      {usageData && (
        <div className="bg-slate-900/70 border border-white/10 rounded-2xl p-6 shadow-xl space-y-5">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
              <span className="text-xs font-semibold uppercase tracking-wider text-indigo-400">
                Active Subscription Plan
              </span>
              <h2 className="text-xl font-bold text-white mt-1">
                {usageData.currentPlan.name} — $
                {billingInterval === 'annual'
                  ? usageData.currentPlan.annualMonthlyPriceUsd
                  : usageData.currentPlan.monthlyPriceUsd}
                /mo
              </h2>
            </div>
            <div className="flex flex-wrap gap-4 text-xs text-slate-300">
              <div className="px-3.5 py-2 rounded-xl bg-white/5 border border-white/10">
                Companies / Agents:{' '}
                <strong className="text-white">
                  {usageData.usage.companyCount} / {usageData.usage.maxCompanies}
                </strong>
              </div>
              <div className="px-3.5 py-2 rounded-xl bg-white/5 border border-white/10">
                Workspace Seats:{' '}
                <strong className="text-white">
                  {usageData.usage.seatCount} / {usageData.usage.maxSeats}
                </strong>
              </div>
              <div className="px-3.5 py-2 rounded-xl bg-white/5 border border-white/10">
                Overage Estimate:{' '}
                <strong className="text-emerald-400">${usageData.usage.overageCostUsd}</strong>
              </div>
            </div>
          </div>

          {/* Minute Meter Progress Bar */}
          <div>
            <div className="flex justify-between text-xs font-medium text-slate-300 mb-2">
              <span>
                Voice Minutes Used: <strong>{usageData.usage.usedMinutes.toLocaleString()}</strong> /{' '}
                {usageData.usage.includedMinutes.toLocaleString()} mins (
                {usageData.usage.totalCalls} calls)
              </span>
              <span>{usageData.usage.utilizationPercent}% utilized</span>
            </div>
            <div className="w-full h-3 bg-slate-950 rounded-full overflow-hidden border border-white/10">
              <div
                className={`h-full transition-all duration-500 ${
                  usageData.usage.limitExceeded
                    ? 'bg-rose-500'
                    : usageData.usage.limitWarning
                      ? 'bg-amber-500'
                      : 'bg-indigo-500'
                }`}
                style={{ width: `${Math.max(2, usageData.usage.utilizationPercent)}%` }}
              />
            </div>
            {usageData.usage.limitWarning && (
              <p className="text-xs text-amber-400 mt-2 flex items-center gap-1.5">
                <AlertTriangle className="w-4 h-4" /> You have used over 80% of your included monthly voice minutes.
              </p>
            )}
          </div>
        </div>
      )}

      {/* 4-Tier Plan Cards */}
      <div className="space-y-4">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
          <h3 className="text-lg font-semibold text-white">Subscription Plans</h3>
          <div className="flex items-center gap-2">
            <input
              type="text"
              value={couponCode}
              onChange={(e) => setCouponCode(e.target.value)}
              placeholder="Promo code (e.g. FONIO20)"
              className="bg-slate-900 border border-white/10 rounded-xl px-3 py-1.5 text-xs text-white outline-none"
            />
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          {plans.map((plan) => {
            const isCurrent = usageData?.currentPlan.id === plan.id;
            const displayPrice =
              billingInterval === 'annual' ? plan.annualMonthlyPriceUsd : plan.monthlyPriceUsd;
            return (
              <motion.div
                key={plan.id}
                whileHover={{ y: -3 }}
                className={`rounded-2xl p-6 border flex flex-col justify-between ${
                  isCurrent
                    ? 'bg-indigo-950/30 border-indigo-500/50 shadow-lg shadow-indigo-500/10'
                    : 'bg-white/[0.02] border-white/10'
                }`}
              >
                <div>
                  <div className="flex items-center justify-between">
                    <h4 className="text-base font-bold text-white">{plan.name}</h4>
                    {isCurrent && (
                      <span className="text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full bg-indigo-500/20 text-indigo-300 border border-indigo-500/30">
                        Current
                      </span>
                    )}
                  </div>
                  <div className="mt-4 flex items-baseline gap-1">
                    <span className="text-3xl font-extrabold text-white">${displayPrice}</span>
                    <span className="text-xs text-slate-400">/ month</span>
                  </div>
                  <p className="text-xs text-indigo-400 font-medium mt-1">
                    {plan.includedMinutes.toLocaleString()} minutes included
                  </p>

                  <ul className="mt-5 space-y-2.5 text-xs text-slate-300">
                    {plan.features.map((feat, idx) => (
                      <li key={idx} className="flex items-start gap-2">
                        <CheckCircle2 className="w-4 h-4 text-emerald-400 shrink-0 mt-0.5" />
                        <span>{feat}</span>
                      </li>
                    ))}
                  </ul>
                </div>

                <button
                  onClick={() => handleSelectPlan(plan.id)}
                  disabled={isCurrent}
                  className={`mt-6 w-full py-2.5 rounded-xl text-xs font-semibold transition-colors ${
                    isCurrent
                      ? 'bg-white/5 text-slate-500 cursor-default'
                      : 'bg-indigo-600 hover:bg-indigo-500 text-white'
                  }`}
                >
                  {isCurrent ? 'Active Plan' : `Switch to ${plan.name}`}
                </button>
              </motion.div>
            );
          })}
        </div>
      </div>

      {/* Team Management & RBAC Section */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <div className="bg-slate-900/60 border border-white/10 rounded-2xl p-6 space-y-5">
          <div className="flex items-center justify-between">
            <h3 className="text-lg font-semibold text-white flex items-center gap-2">
              <Users className="w-5 h-5 text-indigo-400" />
              Team Members & RBAC Roles
            </h3>
            <span className="text-xs text-slate-400">
              {team.length} / {usageData?.usage.maxSeats || 2} seats
            </span>
          </div>

          <form onSubmit={handleInviteMember} className="grid grid-cols-1 sm:grid-cols-3 gap-3">
            <input
              required
              type="text"
              placeholder="Colleague Name"
              value={inviteName}
              onChange={(e) => setInviteName(e.target.value)}
              className="bg-slate-950 border border-white/10 rounded-xl px-3 py-2 text-xs text-white outline-none"
            />
            <input
              required
              type="email"
              placeholder="colleague@company.com"
              value={inviteEmail}
              onChange={(e) => setInviteEmail(e.target.value)}
              className="bg-slate-950 border border-white/10 rounded-xl px-3 py-2 text-xs text-white outline-none"
            />
            <div className="flex gap-2">
              <select
                value={inviteRole}
                onChange={(e) => setInviteRole(e.target.value as 'admin' | 'member')}
                className="bg-slate-950 border border-white/10 rounded-xl px-2.5 py-2 text-xs text-white outline-none"
              >
                <option value="member">Member</option>
                <option value="admin">Admin</option>
              </select>
              <button
                type="submit"
                disabled={inviting}
                className="flex-1 bg-indigo-600 hover:bg-indigo-500 text-white rounded-xl px-3 py-2 text-xs font-medium flex items-center justify-center gap-1"
              >
                <UserPlus className="w-3.5 h-3.5" />
                Invite
              </button>
            </div>
          </form>

          <div className="divide-y divide-white/5">
            {team.map((member) => (
              <div key={member._id} className="py-3 flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-white">{member.name}</p>
                  <p className="text-xs text-slate-400">{member.email}</p>
                </div>
                <div className="flex items-center gap-3">
                  <span className="px-2.5 py-1 rounded-md text-[11px] font-semibold uppercase bg-indigo-500/10 text-indigo-300 border border-indigo-500/20">
                    {member.role}
                  </span>
                  <button
                    onClick={() => handleRemoveMember(member._id)}
                    className="p-1.5 text-slate-400 hover:text-rose-400 rounded-lg hover:bg-rose-500/10 transition-colors"
                    title="Remove Member"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* GDPR Privacy & Security Audit Log Card */}
        <div className="bg-slate-900/60 border border-white/10 rounded-2xl p-6 space-y-5">
          <div className="flex items-center justify-between">
            <h3 className="text-lg font-semibold text-white flex items-center gap-2">
              <Shield className="w-5 h-5 text-emerald-400" />
              GDPR Privacy & Security Audit Trail
            </h3>
          </div>

          <div className="flex flex-wrap gap-3">
            <button
              onClick={handleGdprExport}
              className="flex items-center gap-2 px-3.5 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs font-medium text-slate-200 transition-colors"
            >
              <Download className="w-4 h-4 text-indigo-400" />
              Export All Workspace Data (GDPR Art. 20)
            </button>
            <button
              onClick={handleGdprEraseCalls}
              className="flex items-center gap-2 px-3.5 py-2 rounded-xl bg-rose-500/10 hover:bg-rose-500/20 border border-rose-500/30 text-xs font-medium text-rose-300 transition-colors"
            >
              <Trash2 className="w-4 h-4" />
              Erase Call History (Right to Erasure)
            </button>
          </div>

          <div className="max-h-56 overflow-y-auto space-y-2 pr-1">
            {auditLogs.slice(0, 12).map((log) => (
              <div
                key={log._id}
                className="p-2.5 rounded-lg bg-slate-950/70 border border-white/5 flex items-center justify-between text-xs"
              >
                <div>
                  <span className="font-mono text-indigo-300 font-medium">{log.action}</span>
                  <span className="text-slate-400 ml-2">by {log.actorEmail}</span>
                </div>
                <span className="text-[11px] text-slate-500">
                  {new Date(log.createdAt).toLocaleTimeString([], {
                    hour: '2-digit',
                    minute: '2-digit',
                  })}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Admin Back-Office Overview (Tenants, Usage, MRR) */}
      {adminOverview && (
        <div className="bg-slate-900/60 border border-white/10 rounded-2xl p-6 space-y-5">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
            <div>
              <h3 className="text-lg font-semibold text-white flex items-center gap-2">
                <Building2 className="w-5 h-5 text-indigo-400" />
                Back-Office Admin Panel (Multi-Tenant Usage & Revenue)
              </h3>
              <p className="text-xs text-slate-400">
                Live platform-wide telemetry across all workspaces.
              </p>
            </div>
            <div className="flex items-center gap-4 text-xs">
              <span className="px-3 py-1.5 rounded-lg bg-emerald-500/10 text-emerald-300 border border-emerald-500/20 font-semibold">
                Est. MRR: ${adminOverview.estimatedMrrUsd.toLocaleString()}/mo
              </span>
              <span className="px-3 py-1.5 rounded-lg bg-white/5 text-slate-300 border border-white/10">
                Tenants: {adminOverview.totalTenants}
              </span>
            </div>
          </div>

          <div className="overflow-x-auto rounded-xl border border-white/10">
            <table className="w-full text-left text-xs text-slate-300">
              <thead className="bg-white/5 uppercase text-slate-400 border-b border-white/10">
                <tr>
                  <th className="py-3 px-4">Tenant Workspace</th>
                  <th className="py-3 px-4">Plan</th>
                  <th className="py-3 px-4">Users</th>
                  <th className="py-3 px-4">Companies</th>
                  <th className="py-3 px-4">Total Calls</th>
                  <th className="py-3 px-4">Minutes Used</th>
                  <th className="py-3 px-4 text-right">MRR</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-white/5">
                {adminOverview.tenants.map((t) => (
                  <tr key={t.tenantName} className="hover:bg-white/[0.02]">
                    <td className="py-3 px-4 font-medium text-white flex items-center gap-2">
                      <Activity className="w-3.5 h-3.5 text-indigo-400" />
                      {t.tenantName}
                    </td>
                    <td className="py-3 px-4">{t.plan}</td>
                    <td className="py-3 px-4">{t.usersCount}</td>
                    <td className="py-3 px-4">{t.companiesCount}</td>
                    <td className="py-3 px-4">{t.callsCount}</td>
                    <td className="py-3 px-4">{t.minutesUsed} mins</td>
                    <td className="py-3 px-4 text-right font-semibold text-emerald-400">
                      ${t.monthlyRevenueUsd}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
};

export default Billing;
