import { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { ArrowLeft, Lock } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import StatusPill from '@/components/workshop/StatusPill';
import { useAccount } from '@/lib/AccountContext';
import { adapters } from '@/services/serviceConfig';

const ENTITY_MAP = {
  quotes: 'Quote', orders: 'Order', 'completed-covers': 'CompletedCover', designs: 'DesignConfiguration',
};
const FIELDS = {
  Quote: ['quote_number', 'amount', 'approval_status', 'sent_date', 'expiry_date', 'funding_type'],
  Order: ['order_number', 'production_status', 'payment_status', 'funding_approval_status', 'due_date'],
  CompletedCover: ['cover_reference', 'material', 'main_colour', 'inspection_result', 'fit_review_result', 'completion_date', 'delivery_date'],
  DesignConfiguration: ['concept_name', 'design_category', 'main_colour', 'accent_colour', 'finish', 'concept_status'],
};

export default function PortalDetail({ section }) {
  const { [`${section === 'completed-covers' ? 'coverId' : section === 'quotes' ? 'quoteId' : section === 'orders' ? 'orderId' : 'designId'}`]: id } = useParams();
  const { account } = useAccount();
  const [item, setItem] = useState(null);
  const entity = ENTITY_MAP[section];

  useEffect(() => {
    if (!account?.customer_uuid || !entity || !id) { setItem(null); return; }
    adapters.database.filter(entity, { uuid: id }).then(r => setItem(r[0]));
  }, [id, account, entity]);

  if (!account) return <LoadingPanel label="Loading" />;
  if (!item) return <LoadingPanel label="Loading record" />;

  // Enforce ownership — never rely on URL predictability.
  if (item.customer_uuid !== account.customer_uuid) {
    return (
      <div className="panel mx-auto mt-12 max-w-lg p-8 text-center">
        <Lock className="mx-auto h-10 w-10 text-red-400" />
        <h2 className="mt-4 text-lg font-semibold text-white">Not your record</h2>
        <p className="mt-2 text-sm text-shire-text-secondary">You can only view your own records.</p>
        <Link to="/portal" className="btn-primary mt-4">Back to portal</Link>
      </div>
    );
  }

  const fields = FIELDS[entity] || [];
  // Customers never see CAD/STL/STEP/print files or cost internals.
  const safeFields = fields.filter(f => !['cad_file_url', 'print_file_url', 'line_items', 'invoice_status'].includes(f));

  return (
    <>
      <Link to="/portal" className="mb-4 inline-flex items-center gap-1 text-sm text-slate-400 hover:text-violet-300"><ArrowLeft className="h-4 w-4" />Back to portal</Link>
      <PageHeader eyebrow="Customer Portal" title={item[fields[0]] || 'Record'} />
      <div className="panel max-w-2xl p-6">
        <dl className="space-y-2 text-sm">
          {safeFields.map(f => (
            <div key={f} className="flex justify-between border-b border-shire-border pb-2">
              <dt className="text-shire-text-muted capitalize">{f.replace(/_/g, ' ')}</dt>
              <dd className="text-slate-200">{typeof item[f] === 'number' && f.includes('amount') ? `$${item[f].toFixed(2)}` : String(item[f] ?? '—')}</dd>
            </div>
          ))}
        </dl>
        {entity === 'CompletedCover' && <p className="mt-4 text-xs text-shire-text-muted">Internal CAD, STL, STEP and print files are not shared with customers.</p>}
      </div>
    </>
  );
}