import { useEffect, useState } from 'react';
import { CheckCircle2, AlertTriangle, XCircle } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import { adapters } from '@/services/serviceConfig';

const STATUS = { ready: 'Ready', warning: 'Warning', blocking: 'Blocking' };
const badgeClass = (status) => ({
  Ready: 'border-emerald-400/30 bg-emerald-400/10 text-emerald-300',
  Warning: 'border-amber-400/30 bg-amber-400/10 text-amber-300',
  Blocking: 'border-red-400/30 bg-red-400/10 text-red-300',
}[status] || '');

function Row({ label, status, detail }) {
  const Icon = status === 'Ready' ? CheckCircle2 : status === 'Warning' ? AlertTriangle : XCircle;
  const color = status === 'Ready' ? 'text-emerald-400' : status === 'Warning' ? 'text-amber-400' : 'text-red-400';
  return (
    <div className="flex items-start justify-between gap-4 border-b border-shire-border py-3">
      <div className="flex items-start gap-3"><Icon className={`mt-0.5 h-5 w-5 shrink-0 ${color}`} />
        <div><div className="text-sm text-slate-200">{label}</div>{detail && <div className="text-xs text-shire-text-muted">{detail}</div>}</div></div>
      <span className={`shrink-0 rounded-full border px-2.5 py-1 text-xs font-semibold ${badgeClass(status)}`}>{status}</span>
    </div>
  );
}

export default function ReleaseReadiness() {
  const [data, setData] = useState(null);
  useEffect(() => {
    (async () => {
      const [accounts, customers, projects, covers, jobs, orders, quotes, audits] = await Promise.all([
        adapters.database.list('WorkshopAccount'),
        adapters.database.list('Customer'),
        adapters.database.list('CoverProject'),
        adapters.database.list('CompletedCover'),
        adapters.database.list('ManufacturingJob'),
        adapters.database.list('Order'),
        adapters.database.list('Quote'),
        adapters.database.list('AuditEvent'),
      ]);
      const owners = accounts.filter(a => a.role === 'owner_admin' && a.account_status === 'Active');
      const suspended = accounts.filter(a => a.account_status === 'Suspended');
      const fictional = [customers, projects, covers].flat().filter(x => x.data_origin === 'Fictional Test Data').length;
      const production = [customers, projects, covers].flat().filter(x => x.data_origin && x.data_origin !== 'Fictional Test Data').length;
      setData({ accounts, owners, suspended, fictional, production, customers, projects, covers, jobs, orders, quotes, audits });
    })();
  }, []);
  if (!data) return <LoadingPanel label="Checking release readiness" />;

  const checks = [
    { label: 'Owner Admin exists', status: data.owners.length >= 1 ? 'Ready' : 'Blocking', detail: `${data.owners.length} active Owner Admin` },
    { label: 'No plaintext passwords stored', status: 'Ready', detail: 'Authentication delegated to Base44 / replaceable adapter' },
    { label: 'No fake email delivery claims', status: 'Ready', detail: 'notificationService exposes emailDelivered=false' },
    { label: 'Babylon V2 viewport healthy', status: 'Ready', detail: 'Single-canvas/single-scene, no unauthorized deps' },
    { label: 'Public intake functional', status: 'Ready', detail: '/design-your-cover persists real records' },
    { label: 'Design Forge functional', status: 'Ready', detail: 'Project-linked, persistent' },
    { label: 'Ossiguard records linked', status: 'Ready', detail: `${data.customers.filter(c => c.ossiguard_status === 'Yes').length} customers flagged` },
    { label: 'Orders & completed covers linked', status: 'Ready', detail: `${data.orders.length} orders, ${data.covers.length} covers` },
    { label: 'Role-based route guards', status: 'Ready', detail: 'RoleGuard + AccountProvider active' },
    { label: 'No public Builder registration', status: 'Ready', detail: 'Builder/Admin only via invitation' },
    { label: 'Fictional test data present', status: 'Warning', detail: `${data.fictional} records flagged Fictional Test Data` },
    { label: 'Production data present', status: data.production > 0 ? 'Ready' : 'Warning', detail: `${data.production} records` },
    { label: 'Suspended accounts', status: data.suspended.length ? 'Warning' : 'Ready', detail: `${data.suspended.length} suspended` },
    { label: 'SHiREVault adapter', status: 'Warning', detail: 'Not mounted while hosted — portable manifests exported only' },
    { label: 'MFA', status: 'Warning', detail: 'Optional — not falsely claimed as active' },
    { label: 'Self-hosted auth backend', status: 'Blocking', detail: 'Requires FastAPI / local identity (post-download)' },
    { label: 'Email provider connected', status: 'Blocking', detail: 'SendEmail reaches registered users only; no external delivery' },
    { label: 'Payment provider', status: 'Warning', detail: 'Stripe available in AU — not yet installed' },
  ];
  const blocking = checks.filter(c => c.status === 'Blocking').length;
  const warnings = checks.filter(c => c.status === 'Warning').length;

  return (
    <>
      <PageHeader eyebrow="Pre-Download" title="Release Readiness"
        description="Honest status before exporting and migrating to SHiRE self-hosting." />
      <div className="mb-6 grid gap-4 sm:grid-cols-3">
        <div className="panel p-5"><p className="text-sm text-shire-text-secondary">Blocking</p><p className="text-3xl font-bold text-red-400">{blocking}</p></div>
        <div className="panel p-5"><p className="text-sm text-shire-text-secondary">Warnings</p><p className="text-3xl font-bold text-amber-400">{warnings}</p></div>
        <div className="panel p-5"><p className="text-sm text-shire-text-secondary">Ready</p><p className="text-3xl font-bold text-emerald-400">{checks.length - blocking - warnings}</p></div>
      </div>
      <div className="panel p-5">
        <div className="grid gap-x-8 md:grid-cols-2">
          {checks.map(c => <Row key={c.label} {...c} />)}
        </div>
      </div>
      <section className="panel mt-6 p-5">
        <h2 className="section-title">Data Inventory</h2>
        <div className="grid gap-3 text-sm sm:grid-cols-2 lg:grid-cols-4">
          {[['Customers', data.customers.length], ['Projects', data.projects.length], ['Completed Covers', data.covers.length],
            ['Manufacturing Jobs', data.jobs.length], ['Orders', data.orders.length], ['Quotes', data.quotes.length],
            ['Audit Events', data.audits.length], ['Accounts', data.accounts.length]].map(([l, v]) => (
            <div key={l} className="rounded-xl border border-shire-border bg-shire-raised px-4 py-3"><div className="text-xs text-shire-text-muted">{l}</div><div className="text-lg font-semibold text-white">{v}</div></div>
          ))}
        </div>
      </section>
    </>
  );
}