import type { ClientView } from '@/lib/client-view';
import type { Comment } from '@/db/schema';
import { RefreshCw } from 'lucide-react';
import { PhaseTimeline } from './phase-timeline';
import { PaymentStatus } from './payment-status';
import { DocumentsSection } from './documents-section';
import { NotesSection } from './notes-section';
import { TranscriptsSection } from './transcripts-section';
import { PhaseViewToggle } from './client/kanban/PhaseViewToggle';
import { OffersSection } from './client/OffersSection';
import { MilestoneStepper } from './client/MilestoneStepper';
import { ChatProvider } from './client/ChatProvider';
import { ChatPanel } from './client/ChatPanel';

interface ClientDashboardProps {
  view: ClientView;
  token: string;
  comments: Comment[];
  /** When rendered inside the multi-project tabs wrapper, the page already
   *  provides the portal header + footer — skip them here to avoid duplicates. */
  embedded?: boolean;
}

export function ClientDashboard({ view, token, comments, embedded = false }: ClientDashboardProps) {
  // Determine payment display mode based on active offers
  const retainerOffer = view.activeOffers?.find((o) => o.offer_type === "retainer");
  const hasRetainer = !!retainerOffer;

  const paymentLabel = hasRetainer ? "Totale Pagamento Mensile" : "Totale Investimento";
  const paymentOverrideAmount = hasRetainer && retainerOffer?.accepted_total
    ? retainerOffer.accepted_total
    : undefined;

  return (
    <ChatProvider phases={view.phases} clientId={view.client.id}>
      <div className={embedded ? "" : "min-h-screen bg-background"}>
        {/* Header portale — iamcavalli · Client Portal | brand | area protetta */}
        {!embedded && (
          <header className="sticky top-0 z-50 flex flex-col items-center gap-4 border-b border-border-light bg-card px-6 py-5 shadow-card md:flex-row md:justify-between md:px-8">
            <div className="flex w-full items-center gap-3 md:w-auto">
              <span className="text-xs font-bold uppercase tracking-widest text-muted-foreground">
                iamcavalli
              </span>
              <span className="text-border">|</span>
              <span className="text-xs font-medium text-muted-foreground">Client Portal</span>
            </div>

            <div className="text-center">
              <h1 className="text-xl font-bold tracking-tight text-foreground">
                {view.client.brand_name}
              </h1>
            </div>

            <div className="hidden items-center gap-2 rounded-full border border-emerald-100 bg-emerald-50 px-3 py-1 text-[11px] text-emerald-700 dark:border-emerald-500/20 dark:bg-emerald-500/10 dark:text-emerald-400 md:flex">
              <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-emerald-500" />
              Area Riservata Protetta
            </div>
          </header>
        )}

        {/* Milestone stepper — nascosto per retainer (fasi non tracciate) */}
        {!hasRetainer && (
          <MilestoneStepper phases={view.phases} globalProgress={view.global_progress_pct} />
        )}

        {/* Layout principale */}
        <div className="max-w-[1400px] mx-auto px-4 sm:px-6 py-8 lg:py-10">
          <div className="flex flex-col lg:flex-row gap-8">

            {/* ── Sidebar sinistra ── */}
            <aside className="w-full lg:w-72 shrink-0 order-2 lg:order-1">
              <div className="lg:sticky lg:top-[89px] space-y-6">

                {/* 1° Offerte Attive */}
                {view.activeOffers && view.activeOffers.length > 0 && (
                  <div>
                    <h2 className="text-xs font-bold text-muted-foreground uppercase tracking-wider mb-3">Offerte Attive</h2>
                    <OffersSection offers={view.activeOffers} />
                  </div>
                )}

                {/* 2° Pagamenti */}
                <div>
                  <h2 className="text-xs font-bold text-muted-foreground uppercase tracking-wider mb-3">Pagamenti</h2>
                  <PaymentStatus
                    accepted_total={view.client.accepted_total}
                    payments={view.payments}
                    totalLabel={paymentLabel}
                    overrideAmount={paymentOverrideAmount}
                    hideRows={hasRetainer}
                  />
                </div>

                {/* 3° Documenti & File */}
                <div>
                  <h2 className="text-xs font-bold text-muted-foreground uppercase tracking-wider mb-3">Documenti & File</h2>
                  <DocumentsSection documents={view.documents} />
                </div>

                {view.notes.length > 0 && (
                  <div>
                    <h2 className="text-xs font-bold text-muted-foreground uppercase tracking-wider mb-3">Note & Decisioni</h2>
                    <NotesSection notes={view.notes} />
                  </div>
                )}

                {view.transcripts.length > 0 && (
                  <div>
                    <h2 className="text-xs font-bold text-muted-foreground uppercase tracking-wider mb-3">Transcript Chiamate</h2>
                    <TranscriptsSection transcripts={view.transcripts} />
                  </div>
                )}
              </div>
            </aside>

            {/* ── Contenuto principale ── */}
            <main className="flex-1 min-w-0 order-1 lg:order-2 space-y-12">
              {hasRetainer ? (
                <div>
                  <h2 className="text-lg font-bold text-foreground tracking-tight mb-4">
                    Fasi del Progetto
                  </h2>
                  <div className="flex flex-col items-center justify-center gap-4 rounded-xl border border-dashed border-border bg-muted px-8 py-12 text-center shadow-card">
                    <span className="flex h-11 w-11 items-center justify-center rounded-full bg-card border border-border-light">
                      <RefreshCw className="h-5 w-5 text-muted-foreground" />
                    </span>
                    <div className="space-y-1.5">
                      <p className="text-sm font-semibold text-foreground">Servizio in abbonamento ricorrente</p>
                      <p className="text-xs text-muted-foreground max-w-xs leading-relaxed">
                        Non ci sono fasi di progetto da tracciare. Le fasi compaiono qui quando viene avviata un&apos;offerta a progetto.
                      </p>
                    </div>
                  </div>
                </div>
              ) : (
                <PhaseViewToggle
                  timelineView={<PhaseTimeline phases={view.phases} token={token} />}
                  phases={view.phases}
                  token={token}
                />
              )}
              {/* Chat "Messaggi & Revisioni" moved to slide-in panel (FAB bottom-right) */}
            </main>

          </div>
        </div>

        <footer className="mt-10 py-10 text-center text-xs text-muted-foreground">
          Questa è la tua dashboard privata — non condividere il link.
        </footer>

        {/* Floating chat panel — FAB + slide-in panel */}
        <ChatPanel token={token} comments={comments} />
      </div>
    </ChatProvider>
  );
}
