import { useEffect, useState } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { ArrowLeft, Heart, MessageSquare, CheckCircle2 } 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';
import { auditService } from '@/services/auditService';

export default function PortalProject() {
  const { projectId } = useParams();
  const { account } = useAccount();
  const nav = useNavigate();
  const [project, setProject] = useState(null);
  const [designs, setDesigns] = useState(null);
  const [quote, setQuote] = useState(null);
  const [toast, setToast] = useState('');

  useEffect(() => {
    if (!account?.customer_uuid) return;
    (async () => {
      const ps = await adapters.database.filter('CoverProject', { uuid: projectId });
      const p = ps[0];
      setProject(p);
      if (p && p.customer_uuid === account.customer_uuid) {
        setDesigns(await adapters.database.filter('DesignConfiguration', { project_uuid: projectId }));
        if (p.uuid) {
          const qs = await adapters.database.filter('Quote', { project_uuid: projectId });
          setQuote(qs[0] || null);
        }
      }
    })();
  }, [projectId, account]);

  if (!account) return <LoadingPanel label="Loading" />;
  if (!project) return <LoadingPanel label="Loading request" />;

  if (project.customer_uuid !== account.customer_uuid) {
    return (
      <div className="panel mx-auto mt-12 max-w-lg p-8 text-center">
        <h2 className="text-lg font-semibold text-white">This request is not yours</h2>
        <p className="mt-2 text-sm text-shire-text-secondary">You can only view your own cover requests.</p>
        <Link to="/portal" className="btn-primary mt-4">Back to my portal</Link>
      </div>
    );
  }

  const releasedDesigns = (designs || []).filter(d => d.concept_status === 'Sent to Customer' || d.concept_status === 'Customer Preferred' || d.concept_status === 'Approved for Quote');

  const preferDesign = async (d) => {
    await adapters.database.update('DesignConfiguration', d.id, { concept_status: 'Customer Preferred', customer_feedback: (d.customer_feedback || '') + ' [Marked preferred]' });
    auditService.record('design_preference', 'DesignConfiguration', d.uuid, 'Customer marked design as preferred', account.display_name);
    setToast('Preference saved. This confirms visual direction only — it does not mean CAD, manufacturing or NDIS approval is complete.');
    setTimeout(() => setToast(''), 5000);
    setDesigns(await adapters.database.filter('DesignConfiguration', { project_uuid: projectId }));
  };

  const approveForQuote = async (d) => {
    await adapters.database.update('DesignConfiguration', d.id, { concept_status: 'Approved for Quote', approved_for_quote: true });
    auditService.record('design_approved', 'DesignConfiguration', d.uuid, 'Customer approved design for quote', account.display_name);
    setToast('Design approved for quote. A quote will be prepared for you.');
    setTimeout(() => setToast(''), 4000);
    setDesigns(await adapters.database.filter('DesignConfiguration', { project_uuid: projectId }));
  };

  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 my portal</Link>
      <PageHeader eyebrow="My Request" title={`Request ${project.project_id}`} description="Your cover request summary and design concepts released to you." />

      {toast && <div className="mb-4 rounded-lg border border-shire-purple/40 bg-shire-purple/10 p-3 text-sm text-violet-200">{toast}</div>}

      <div className="grid gap-6 lg:grid-cols-2">
        <section className="panel p-5">
          <h2 className="section-title">Request Summary</h2>
          <dl className="space-y-2 text-sm">
            <div className="flex justify-between"><dt className="text-shire-text-muted">Status</dt><dd><StatusPill tone="cyan">{project.status}</StatusPill></dd></div>
            <div className="flex justify-between"><dt className="text-shire-text-muted">Reason for cover</dt><dd className="text-slate-200">{project.reason_for_cover || '—'}</dd></div>
            <div className="flex justify-between"><dt className="text-shire-text-muted">Due date</dt><dd className="text-slate-200">{project.due_date || '—'}</dd></div>
          </dl>
          {project.status === 'Awaiting customer clarification' && (
            <div className="mt-4 rounded-lg border border-amber-400/30 bg-amber-400/10 p-3 text-sm text-amber-200">We need some details from you. Please contact SHiRE to provide the requested information.</div>
          )}
        </section>

        <section className="panel p-5">
          <h2 className="section-title">Quote</h2>
          {quote ? (
            <dl className="space-y-2 text-sm">
              <div className="flex justify-between"><dt className="text-shire-text-muted">Quote number</dt><dd className="text-slate-200">{quote.quote_number}</dd></div>
              <div className="flex justify-between"><dt className="text-shire-text-muted">Amount</dt><dd className="text-slate-200">${quote.amount?.toFixed(2)}</dd></div>
              <div className="flex justify-between"><dt className="text-shire-text-muted">Status</dt><dd><StatusPill tone={quote.approval_status === 'Approved' ? 'green' : 'amber'}>{quote.approval_status}</StatusPill></dd></div>
              <div className="flex justify-between"><dt className="text-shire-text-muted">Expiry</dt><dd className="text-slate-200">{quote.expiry_date || '—'}</dd></div>
            </dl>
          ) : <p className="text-sm text-shire-text-muted">No quote prepared yet.</p>}
        </section>
      </div>

      <section className="panel mt-6 p-5">
        <h2 className="section-title">Design Concepts Released to You</h2>
        {releasedDesigns.length === 0 ? <p className="text-sm text-shire-text-muted">No design concepts have been released to you yet.</p> : (
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {releasedDesigns.map(d => (
              <div key={d.uuid} className="rounded-xl border border-shire-border bg-shire-raised p-4">
                <div className="mb-2 flex items-center justify-between">
                  <span className="text-sm font-medium text-slate-200">{d.concept_name || `Concept v${d.version}`}</span>
                  <StatusPill tone={d.concept_status === 'Approved for Quote' ? 'green' : d.concept_status === 'Customer Preferred' ? 'cyan' : 'amber'}>{d.concept_status}</StatusPill>
                </div>
                <p className="text-xs text-shire-text-muted mb-3">{d.design_category} · {d.main_colour}</p>
                <div className="flex gap-2">
                  <button className="btn-secondary flex-1" onClick={() => preferDesign(d)}><Heart className="h-4 w-4" />Prefer</button>
                  {d.concept_status !== 'Approved for Quote' && <button className="btn-primary flex-1" onClick={() => approveForQuote(d)}><CheckCircle2 className="h-4 w-4" />Approve for Quote</button>}
                </div>
              </div>
            ))}
          </div>
        )}
        <p className="mt-4 text-xs text-shire-text-muted">Design approval confirms the visual direction only. It does not mean CAD, manufacturing or NDIS approval is complete. Internal CAD, STL, STEP and print files are not shared.</p>
      </section>
    </>
  );
}