import type { ClientView } from '@/lib/client-view';
import type { Comment } from '@/db/schema';
import { Progress } from '@/components/ui/progress';
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 { ChatProvider } from './client/ChatProvider';
import { ChatPanel } from './client/ChatPanel';

interface ClientDashboardProps {
  view: ClientView;
  token: string;
  comments: Comment[];
}

export function ClientDashboard({ view, token, comments }: 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="min-h-screen bg-white">
        {/* Header */}
        <header className="bg-white border-b border-[#e5e5e5] sticky top-0 z-10">
          <div className="max-w-6xl mx-auto px-4 sm:px-6 py-5">
            <div className="flex items-center">
              <span className="text-xs font-semibold tracking-widest text-[#999999] uppercase w-28 shrink-0">
                iamcavalli
              </span>
              <h1 className="flex-1 text-center text-2xl sm:text-3xl font-bold text-[#1a1a1a] tracking-tight">
                {view.client.brand_name}
              </h1>
              <div className="w-28 shrink-0" />
            </div>
          </div>
        </header>

        {/* Barra progresso globale — nascosta per retainer (fasi non tracciate) */}
        {!hasRetainer && (
          <section className="bg-[#f9f9f9] border-b border-[#e5e5e5]">
            <div className="max-w-6xl mx-auto px-4 sm:px-6 py-4">
              <div className="flex items-center justify-between mb-2">
                <p className="text-sm font-semibold text-[#1a1a1a]">Avanzamento Progetto</p>
                <p className="text-sm font-bold text-[#1a1a1a]">{view.global_progress_pct}%</p>
              </div>
              <Progress value={view.global_progress_pct} className="h-2" />
            </div>
          </section>
        )}

        {/* Layout principale */}
        <div className="max-w-6xl mx-auto px-4 sm:px-6 py-8">
          <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-[#71717a] uppercase tracking-wider mb-3">Offerte Attive</h2>
                    <OffersSection offers={view.activeOffers} />
                  </div>
                )}

                {/* 2° Pagamenti */}
                <div>
                  <h2 className="text-xs font-bold text-[#71717a] 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-[#71717a] 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-[#71717a] 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-[#71717a] 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-xs font-bold text-[#71717a] uppercase tracking-wider mb-4">
                    Fasi del Progetto
                  </h2>
                  <div className="flex flex-col items-center justify-center gap-4 rounded-xl border border-dashed border-[#d4d4d4] bg-[#fafafa] px-8 py-12 text-center">
                    <span className="flex h-11 w-11 items-center justify-center rounded-full bg-[#f0f0f0]">
                      <RefreshCw className="h-5 w-5 text-[#71717a]" />
                    </span>
                    <div className="space-y-1.5">
                      <p className="text-sm font-semibold text-[#1a1a1a]">Servizio in abbonamento ricorrente</p>
                      <p className="text-xs text-[#71717a] 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="border-t border-[#e5e5e5] bg-[#f9f9f9] mt-10">
          <div className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
            <p className="text-xs text-[#999999] text-center">
              Questa è la tua dashboard privata — non condividere il link.
            </p>
          </div>
        </footer>

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