'use client'

import * as React from 'react'
import { ArrowRight, ShieldCheck, Beaker, FileCheck, AlertTriangle, RefreshCw, GitBranch, Database, TrendingUp } from 'lucide-react'
import { useRouter } from '@/lib/router'
import { PageShell, PageHero, Section, SectionHeading, Reveal, Eyebrow, Card, DefRow, LabeledDivider, LinkButton, Pill, NumberedStep } from '@/components/site/ui'

const PILLARS = [
  { icon: ShieldCheck, t: 'GMP — Good Manufacturing Practice', d: 'cGMP as defined by FDA 21 CFR 210/211 (drug products), 21 CFR 600 series (biologics), EU GMP EudraLex Volume 4, WHO GMP TRS, ICH Q7 (APIs). Covers organization, personnel, premises, equipment, production, QC, documentation, complaints and recalls.' },
  { icon: Beaker, t: 'GLP — Good Laboratory Practice', d: 'OECD Principles of GLP and 21 CFR 58 for non-clinical safety studies. Ensures study validity, traceability and reconstructibility of toxicity, safety pharmacology and ADME studies submitted to regulators.' },
  { icon: FileCheck, t: 'GDP — Good Distribution Practice', d: 'EU GDP (2013/C 343/01) and WHO GDP guidance. Governs procurement, storage, distribution and transportation of pharmaceutical products, including temperature management, traceability and serialization.' },
  { icon: FileCheck, t: 'ICH Guidelines', d: 'Comprehensive application of ICH Q-series (quality), S-series (safety), E-series (efficacy) and M-series (multidisciplinary) guidelines. Central to global regulatory submissions and lifecycle management.' },
]

const QSYSTEMS = [
  { icon: FileCheck, t: 'Validation', d: 'Process, equipment, utility, cleaning, analytical method and computerized system validation — per ICH Q7, Q8, Q9, Q10 and FDA Process Validation Guidance (2011, lifecycle approach: Process Design, Process Qualification, Continued Process Verification).' },
  { icon: ShieldCheck, t: 'Qualification', d: 'Facility, utility and equipment qualification following the URS → DQ → IQ → OQ → PQ lifecycle. Risk-based qualification per ICH Q9, with documented acceptance criteria and traceability.' },
  { icon: Database, t: 'Documentation', d: 'Site Quality Manual, SOPs, batch records, specifications, validation reports, change control and CAPA records. ALCOA+ data integrity principles. 21 CFR Part 11 and EU GMP Annex 11 for electronic records and signatures.' },
  { icon: AlertTriangle, t: 'Risk management', d: 'ICH Q9 quality risk management applied throughout the lifecycle — FMEA, FMECA, HACCP, fishbone analysis. Risk-based decisions for investigations, change control, supplier management and validation scope.' },
  { icon: RefreshCw, t: 'CAPA', d: 'Corrective action and preventive action (CAPA) system ensuring root-cause identification, sustainable corrective actions and verification of effectiveness. Central to ICH Q10 pharmaceutical quality system.' },
  { icon: AlertTriangle, t: 'Deviation management', d: 'Deviation identification, classification, investigation and closure. Risk-based investigation depth, root-cause analysis, impact assessment on product quality and patient safety.' },
  { icon: GitBranch, t: 'Change control', d: 'Change management covering facility, equipment, process, materials, methods, suppliers and documents. Risk-based regulatory impact assessment — prior approval, notification or internal — per ICH Q12.' },
  { icon: Database, t: 'Data integrity', d: 'ALCOA+ (Attributable, Legible, Contemporaneous, Original, Accurate, plus Complete, Consistent, Enduring, Available). Enforced across paper and electronic systems; validated computerized systems per 21 CFR Part 11 and Annex 11.' },
]

export function QualityPage() {
  const { navigate } = useRouter()
  return (
    <PageShell>
      <PageHero
        index="01"
        eyebrow="Quality assurance"
        title="Quality is designed in."
        highlight="Not inspected in."
        lead="Espandiar&apos;s pharmaceutical quality system implements ICH Q10 across the product lifecycle. This page describes the regulatory frameworks, systems and practices that govern quality at every Espandiar facility."
      />

      {/* Overview */}
      <Section tone="light">
        <SectionHeading
          index="02"
          eyebrow="Quality system overview"
          title="A unified quality"
          highlight="lifecycle."
          lead="ICH Q10 defines the Pharmaceutical Quality System (PQS) as a comprehensive model that integrates GMP, quality risk management (ICH Q9) and pharmaceutical development (ICH Q8) across the product lifecycle."
        />
        <div className="mt-12 grid gap-8 lg:grid-cols-[1.1fr_0.9fr]">
          <Reveal>
            <div className="space-y-5 text-[15px] leading-7 text-muted-foreground">
              <p>
                Pharmaceutical quality is not a single activity — it is a
                system. The objective, as defined by ICH Q10, is to establish
                and maintain a state of control, facilitate continuous
                improvement, and ensure that products meet the quality
                attributes appropriate for their intended use.
              </p>
              <p>
                The PQS applies across four lifecycle stages:
                pharmaceutical development (QbD, CQAs, CPPs, control
                strategy), technology transfer (from R&D to manufacturing and
                between sites), commercial manufacturing (GMP operations,
                continuous verification) and product discontinuation.
              </p>
              <p>
                Underpinning the PQS are two cross-cutting disciplines:
                quality risk management (ICH Q9), which ensures that risk
                decisions are rational and documented; and data integrity
                (ALCOA+), which ensures that all data used to make quality
                decisions are reliable, attributable and reconstructible.
              </p>
              <p>
                The following sections describe each element of our quality
                system. They are based on the regulations and guidelines
                issued by FDA, EMA, ICH, WHO, USP and Ph. Eur., and reflect
                current pharmaceutical industry practice.
              </p>
            </div>
          </Reveal>
          <Reveal delay={0.1}>
            <Card className="bg-[#eef1ec] dark:bg-[#17231f]">
              <Eyebrow>ICH Q10 — four PQS elements</Eyebrow>
              <dl className="mt-6">
                <DefRow term="Process performance & product quality monitoring">Continual assessment of process capability and product quality, including trend analysis and statistical process control.</DefRow>
                <DefRow term="CAPA system">Corrective and preventive action driven by root-cause analysis and verified for effectiveness.</DefRow>
                <DefRow term="Change management">Risk-based assessment of all changes — facility, process, materials, suppliers — with regulatory impact evaluation.</DefRow>
                <DefRow term="Management review">Senior management oversight of PQS performance, with structured quality metrics and trend reporting.</DefRow>
              </dl>
            </Card>
          </Reveal>
        </div>
      </Section>

      {/* Regulatory pillars */}
      <Section tone="dark">
        <SectionHeading
          tone="dark"
          index="03"
          eyebrow="Regulatory frameworks"
          title="The standards we"
          highlight="operate under."
          lead="Pharmaceutical quality is governed by an interlocking framework of national and international regulations. We operate to all of them."
        />
        <div className="mt-12 grid gap-4 md:grid-cols-2">
          {PILLARS.map((p, i) => {
            const Icon = p.icon
            return (
              <Reveal key={p.t} delay={(i % 2) * 0.1}>
                <Card tone="dark" className="h-full">
                  <div className="grid h-12 w-12 place-items-center rounded-2xl bg-white/10 text-white">
                    <Icon className="h-5 w-5" />
                  </div>
                  <h3 className="mt-5 text-lg font-semibold tracking-[-0.02em]">{p.t}</h3>
                  <p className="mt-3 text-sm leading-6 text-white/60">{p.d}</p>
                </Card>
              </Reveal>
            )
          })}
        </div>
      </Section>

      {/* Quality systems */}
      <Section tone="light">
        <SectionHeading
          index="04"
          eyebrow="Quality systems"
          title="The systems that"
          highlight="make quality real."
          lead="Each quality system below is a structured, documented process that turns regulatory requirements into daily operational practice."
        />
        <div className="mt-12 grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          {QSYSTEMS.map((s, i) => {
            const Icon = s.icon
            return (
              <Reveal key={s.t} delay={(i % 4) * 0.08}>
                <Card className="h-full">
                  <div className="grid h-11 w-11 place-items-center rounded-2xl bg-[#0d5d50]/10 text-[#0d5d50] dark:bg-[#8fb9ad]/10 dark:text-[#8fb9ad]">
                    <Icon className="h-5 w-5" />
                  </div>
                  <h3 className="mt-5 text-base font-semibold tracking-[-0.02em]">{s.t}</h3>
                  <p className="mt-3 text-sm leading-6 text-muted-foreground">{s.d}</p>
                </Card>
              </Reveal>
            )
          })}
        </div>
      </Section>

      {/* Validation lifecycle */}
      <Section tone="pearl">
        <SectionHeading
          index="05"
          eyebrow="Validation lifecycle"
          title="Validation is not an event."
          highlight="It is a lifecycle."
          lead="FDA&apos;s 2011 Process Validation Guidance and ICH Q8/Q9/Q10 reframe validation as a continuous activity across three stages."
        />
        <div className="mt-12 space-y-7">
          {[
            { n: '01', t: 'Process design (Stage 1)', d: 'Collect and synthesize knowledge from pharmaceutical development — defining CQAs, identifying CPPs, building the control strategy. Pilot-scale batches, design of experiments (DoE), and risk assessments establish the scientific basis for the commercial process.' },
            { n: '02', t: 'Process qualification (Stage 2)', d: 'Facility, equipment and utility qualification (DQ, IQ, OQ, PQ), followed by Process Performance Qualification (PPQ) — successive batches executed under commercial conditions to demonstrate the process is reproducible and capable.' },
            { n: '03', t: 'Continued process verification (Stage 3)', d: 'Ongoing monitoring of process performance and product quality throughout commercial production. Statistical process control, trend analysis, periodic product quality reviews (PQR), and continuous improvement actions.' },
          ].map((s) => (
            <Reveal key={s.n}>
              <NumberedStep n={s.n} title={s.t}>
                {s.d}
              </NumberedStep>
            </Reveal>
          ))}
        </div>
      </Section>

      {/* Data integrity deep dive */}
      <Section tone="dark">
        <SectionHeading
          tone="dark"
          index="06"
          eyebrow="Data integrity"
          title="ALCOA+"
          highlight="in everything."
          lead="Data integrity is the foundation of every quality decision. Without it, batch release, stability conclusions and regulatory submissions cannot be trusted."
        />
        <div className="mt-12 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {[
            { t: 'Attributable', d: 'Every data point can be traced to the individual who generated it — through signatures, electronic signatures and audit trails.' },
            { t: 'Legible', d: 'Data is recorded in a permanent, readable form. Corrections are made with single-line strikethrough, signed and dated, retaining the original entry.' },
            { t: 'Contemporaneous', d: 'Data is recorded at the time of the activity — not reconstructed from memory after the fact.' },
            { t: 'Original', d: 'The first capture of data (or a true certified copy) is preserved. Electronic primary data is preferred where possible.' },
            { t: 'Accurate', d: 'Data is correct, complete and truthful, with no errors or omissions. Methods and equipment are calibrated and validated.' },
            { t: 'Complete', d: 'All data — including failed runs, repeats and investigations — is retained. No selective reporting.' },
            { t: 'Consistent', d: 'Data is recorded in chronological order, with consistent formats and units, and follows defined procedures.' },
            { t: 'Enduring', d: 'Data is recorded on durable media — validated electronic systems or archival-quality paper — and retained for the required period.' },
            { t: 'Available', d: 'Data is retrievable throughout its retention period, for review by auditors, inspectors and authorized personnel.' },
          ].map((d, i) => (
            <Reveal key={d.t} delay={(i % 3) * 0.08}>
              <Card tone="dark" className="h-full">
                <Pill tone="dark">{`0${i + 1}`}</Pill>
                <h3 className="mt-4 text-base font-semibold tracking-[-0.02em]">{d.t}</h3>
                <p className="mt-2 text-sm leading-6 text-white/60">{d.d}</p>
              </Card>
            </Reveal>
          ))}
        </div>
      </Section>

      {/* Continuous improvement */}
      <Section tone="light">
        <SectionHeading
          index="07"
          eyebrow="Continuous improvement"
          title="Better every cycle."
          highlight="By design."
          lead="ICH Q10 explicitly includes continuous improvement within the PQS. We structure improvement around the Plan-Do-Check-Act cycle, with quality metrics and management review ensuring accountability."
        />
        <div className="mt-12 grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          {[
            { icon: TrendingUp, t: 'Trend analysis', d: 'Statistical process control charts, control limits and trend analysis on CQAs, environmental monitoring, deviations and complaints.' },
            { icon: FileCheck, t: 'Product quality review', d: 'Annual PQR per EU GMP Chapter 1 and ICH Q7 — review of all batches, deviations, changes, complaints, stability and CAPA.' },
            { icon: ShieldCheck, t: 'Management review', d: 'Senior management review of PQS performance metrics, with action items tracked to closure.' },
            { icon: RefreshCw, t: 'PDCA cycle', d: 'Plan-Do-Check-Act applied to every improvement initiative, with documented effectiveness checks.' },
          ].map((c, i) => {
            const Icon = c.icon
            return (
              <Reveal key={c.t} delay={(i % 4) * 0.08}>
                <Card className="h-full">
                  <div className="grid h-11 w-11 place-items-center rounded-2xl bg-[#0d5d50]/10 text-[#0d5d50] dark:bg-[#8fb9ad]/10 dark:text-[#8fb9ad]">
                    <Icon className="h-5 w-5" />
                  </div>
                  <h3 className="mt-5 text-base font-semibold tracking-[-0.02em]">{c.t}</h3>
                  <p className="mt-3 text-sm leading-6 text-muted-foreground">{c.d}</p>
                </Card>
              </Reveal>
            )
          })}
        </div>
      </Section>

      {/* CTA */}
      <Section tone="emerald">
        <div className="grid gap-8 lg:grid-cols-[1.2fr_0.8fr] lg:items-center">
          <Reveal>
            <Eyebrow tone="sage">Quality partnerships</Eyebrow>
            <h2 className="mt-5 text-3xl font-semibold tracking-[-0.04em] sm:text-5xl">
              Audits, inspections and quality agreements.
            </h2>
            <p className="mt-5 max-w-xl text-sm leading-6 text-white/75">
              We welcome customer audits, regulatory inspections and
              third-party certifications. Quality agreements with every
              commercial partner define responsibilities, communication
              and escalation pathways. Contact our quality team for audit
              scheduling and quality agreement negotiation.
            </p>
          </Reveal>
          <Reveal delay={0.1} className="flex flex-wrap gap-3 lg:justify-end">
            <LinkButton variant="light" onClick={() => navigate('contact')}>
              Schedule an audit
              <ArrowRight className="h-4 w-4" />
            </LinkButton>
            <LinkButton variant="outline" className="text-white" onClick={() => navigate('manufacturing')}>
              Manufacturing overview
              <ArrowRight className="h-4 w-4" />
            </LinkButton>
          </Reveal>
        </div>
      </Section>
    </PageShell>
  )
}
