import { useEffect, useRef, useState, useCallback } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Maximize2, Download } from "lucide-react";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";

const DIAGRAMS = [
  {
    title: "1. Platform Architecture Overview",
    description: "High-level view of the multi-tenant marketplace architecture",
    mermaid: `graph TB
    subgraph "Public Internet"
        U[End User / Browser]
    end

    subgraph "Frontend - React SPA"
        TR[TenantProvider<br/>Detects subdomain or ?tenant= param]
        MR[Marketplace Routes<br/>Primary domain]
        WR[White-Label Routes<br/>Tenant subdomain]
        CDPage[CourseDetailPage<br/>+ CheckoutModal]
        RegPage[RegisterPage<br/>Delegate or Company]
    end

    subgraph "Lovable Cloud Backend"
        Auth[Authentication<br/>Email + Password]
        DB[(Database<br/>PostgreSQL + RLS)]
        EF[Edge Functions]
        Storage[File Storage<br/>company-assets bucket]
    end

    subgraph "External"
        Stripe[Stripe API<br/>Per-tenant keys]
        Email[Resend<br/>Transactional Email]
    end

    U --> TR
    TR -->|primary domain| MR
    TR -->|subdomain detected| WR
    MR --> CDPage
    WR --> CDPage
    MR --> RegPage
    CDPage --> EF
    RegPage --> Auth
    RegPage --> DB
    EF --> Stripe
    EF --> DB
    EF --> Email
    Auth --> DB`,
  },
  {
    title: "2. Company → Trainer → Course Data Model",
    description: "How companies, trainers, courses, and venues are linked",
    mermaid: `erDiagram
    training_companies ||--o{ company_branding : "has branding"
    training_companies ||--o{ company_stripe_config : "has Stripe keys"
    training_companies ||--o{ trainer_companies : "employs"
    training_companies ||--o{ venues : "owns"
    training_companies ||--o{ delegates : "has delegates"

    trainers ||--o{ trainer_companies : "works for"
    trainers ||--o{ course_trainers : "teaches"
    trainers ||--o{ trainer_availability_weekly : "weekly schedule"
    trainers ||--o{ trainer_availability_overrides : "date overrides"
    trainers ||--o{ course_bookings : "booked for"

    courses ||--o{ course_trainers : "taught by"
    courses ||--o{ course_venue_schedules : "venue schedule"
    courses ||--o{ course_bookings : "bookings"
    courses ||--o{ course_orders : "orders"

    venues ||--o{ venue_rooms : "has rooms"
    venues ||--o{ venue_yards : "has yards"
    venues ||--o{ course_venue_schedules : "scheduled at"

    course_orders }o--|| courses : "for course"
    course_orders }o--o| training_companies : "via company"
    course_orders }o--o| trainers : "assigned trainer"
    course_orders }o--o| venues : "at venue"`,
  },
  {
    title: "3. Registration Flows",
    description: "Delegate vs Company account registration",
    mermaid: `flowchart TD
    Start([User clicks Register]) --> Choice{Account Type?}

    Choice -->|Delegate Account| MF[Fill: Name, Email, Phone, Password]
    MF --> MAuth[Create Auth User<br/>with full_name metadata]
    MAuth --> MProfile[Auto-create Profile<br/>via DB trigger]
    MProfile --> MSuccess([Delegate Ready<br/>Can browse and book courses])

    Choice -->|Company Account| CF[Fill: Company Name, Address,<br/>VAT, Admin Name, Email, Password]
    CF --> CAuth[Create Auth User<br/>for company admin]
    CAuth --> CProfile[Auto-create Profile<br/>via DB trigger]
    CProfile --> CCompany[Insert training_companies<br/>status = draft]
    CCompany --> CPending([Pending Verification<br/>Admin must approve])
    CPending --> AReview[Admin reviews in CMS]
    AReview -->|Approve| Active([Company Active<br/>Can configure branding + Stripe])
    AReview -->|Reject| Rejected([Registration Rejected])`,
  },
  {
    title: "4. Primary Domain Checkout Flow",
    description: "Booking and payment on the main UTC marketplace site",
    mermaid: `sequenceDiagram
    participant U as Customer
    participant FE as Frontend
    participant EF as create-payment-intent
    participant DB as Database
    participant S as Stripe API
    participant WH as payment-webhook

    U->>FE: Select course + date, click Book
    FE->>FE: Open CheckoutModal<br/>Step 1: Customer details

    U->>FE: Fill name, email, phone, delegates
    FE->>FE: Step 2: Payment form

    FE->>EF: POST {course_id, start_date, customer_*}
    EF->>DB: Lookup course (price_cents, title)
    EF->>DB: No company_id → use platform STRIPE_SECRET_KEY
    EF->>DB: INSERT course_orders (status=pending)
    EF->>S: stripe.paymentIntents.create(amount, gbp)
    S-->>EF: clientSecret + paymentIntent.id
    EF->>DB: UPDATE order with stripe_payment_intent_id
    EF-->>FE: {clientSecret, publishableKey, orderId}

    FE->>S: stripe.confirmPayment(clientSecret)
    S-->>FE: Payment succeeded

    FE->>WH: POST {order_id, payment_intent_id}
    WH->>DB: UPDATE order status = paid
    WH->>DB: INSERT course_bookings (blocks trainer)
    WH-->>FE: {success: true}

    FE->>FE: Step 3: Success screen`,
  },
  {
    title: "5. White-Label Subdomain Checkout Flow",
    description: "Booking via a tenant-branded subdomain with per-tenant Stripe keys",
    mermaid: `sequenceDiagram
    participant U as Customer
    participant FE as Tenant Frontend
    participant TC as TenantContext
    participant EF as create-payment-intent
    participant DB as Database
    participant S as Tenant Stripe

    U->>FE: Visit acme.utc-platform.com
    FE->>TC: Detect subdomain "acme"
    TC->>DB: SELECT company_branding WHERE subdomain=acme
    DB-->>TC: branding + company_id
    TC->>FE: Apply tenant colors, logo, routes

    U->>FE: Browse courses, select date, click Book
    FE->>EF: POST {course_id, company_id=acme_id, ...}

    EF->>DB: Lookup course
    EF->>DB: SELECT company_stripe_config<br/>WHERE company_id=acme_id
    DB-->>EF: tenant stripe_secret_key + publishable_key

    EF->>DB: INSERT course_orders (company_id=acme_id)
    EF->>S: stripe.paymentIntents.create<br/>using TENANT secret key
    S-->>EF: clientSecret

    EF-->>FE: {clientSecret, publishableKey=TENANT_KEY}

    Note over FE: Stripe Elements loads with<br/>tenant's publishable key

    FE->>S: confirmPayment (tenant Stripe)
    S-->>FE: Success

    FE->>EF: payment-webhook confirms
    EF->>DB: Order paid + booking created
    EF->>DB: Deduct company credit if applicable`,
  },
  {
    title: "6. Admin CMS & Company Lifecycle",
    description: "How admins manage companies, trainers, courses, and stripe config",
    mermaid: `flowchart LR
    subgraph "Admin CMS /admin"
        Dash[Dashboard]
        Comp[Companies<br/>View/Approve/Reject]
        Train[Trainers<br/>CRUD + Availability]
        Crs[Courses<br/>CRUD + Venue Schedules]
        Ven[Venues<br/>Rooms + Yards]
        Avail[Availability<br/>Calendar View]
    end

    subgraph "Company Setup Flow"
        Draft[Company registered<br/>status=draft] --> Review[Admin reviews]
        Review --> Approve[Set status=active]
        Approve --> Brand[Configure Branding<br/>Logo, colors, subdomain]
        Brand --> StripeK[Add Stripe Keys<br/>Publishable + Secret]
        StripeK --> Live[Tenant site LIVE<br/>subdomain.domain.com]
    end

    subgraph "Course Assignment"
        CreateCourse[Create Course] --> AssignTrainer[Link Trainer to Course]
        AssignTrainer --> AssignVenue[Set Venue Schedule<br/>Room/Yard per day+session]
        AssignVenue --> SetPrice[Set Price in Pence]
        SetPrice --> Publish[is_active = true<br/>Visible on marketplace]
    end

    Comp --> Draft
    Crs --> CreateCourse`,
  },
  {
    title: "7. Availability & Booking Logic",
    description: "How trainer availability is determined and blocked by bookings",
    mermaid: `flowchart TD
    Start([Check if trainer available<br/>for course on date]) --> Weekly{Weekly schedule<br/>day_of_week available?}
    Weekly -->|No| Unavail([Unavailable])
    Weekly -->|Yes| Override{Any date override?}

    Override -->|Override: unavailable| Unavail
    Override -->|Override: available| CheckBook{Existing booking<br/>on that date?}
    Override -->|No override| CheckBook

    CheckBook -->|Booking exists<br/>status=confirmed| Unavail
    CheckBook -->|No booking| BankHol{Is UK bank holiday?}

    BankHol -->|Yes| Unavail
    BankHol -->|No| MultiDay{Multi-day course?}

    MultiDay -->|Yes| CheckAll[Check all consecutive<br/>days for conflicts]
    CheckAll --> AllClear{All days clear?}
    AllClear -->|No| Unavail
    AllClear -->|Yes| Avail([Available ✓])

    MultiDay -->|No| Avail`,
  },
  {
    title: "8. Row-Level Security Model",
    description: "Who can access what data — enforced at database level",
    mermaid: `graph LR
    subgraph "Public Access (no auth)"
        P1[View active courses]
        P2[View company branding]
        P3[View trainer-company links]
        P4[Create orders]
        P5[Register draft company]
    end

    subgraph "Authenticated Users"
        A1[View own profile]
        A2[Update own profile]
        A3[View trainers]
        A4[View venues + rooms + yards]
        A5[View availability]
        A6[View bookings]
    end

    subgraph "Admin / Manager"
        M1[CRUD courses]
        M2[CRUD trainers]
        M3[CRUD venues]
        M4[CRUD availability]
        M5[CRUD bookings]
        M6[CRUD companies]
        M7[CRUD branding]
    end

    subgraph "Admin Only"
        X1[Manage Stripe config]
        X2[Delete records]
        X3[Manage user roles]
        X4[View all profiles]
    end`,
  },
];

// Minimal Mermaid renderer using the CDN
const MermaidDiagram = ({ chart, id }: { chart: string; id: string }) => {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const render = async () => {
      // @ts-ignore
      if (!window.mermaid) {
        const script = document.createElement("script");
        script.src = "https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js";
        script.onload = () => {
          // @ts-ignore
          window.mermaid.initialize({ startOnLoad: false, theme: "neutral", securityLevel: "loose" });
          renderChart();
        };
        document.head.appendChild(script);
      } else {
        renderChart();
      }
    };

    const renderChart = async () => {
      if (!ref.current) return;
      try {
        // @ts-ignore
        const { svg } = await window.mermaid.render(`mermaid-${id}`, chart);
        if (ref.current) ref.current.innerHTML = svg;
      } catch (e) {
        if (ref.current) ref.current.innerHTML = `<pre class="text-destructive text-sm">${e}</pre>`;
      }
    };

    render();
  }, [chart, id]);

  return <div ref={ref} className="overflow-x-auto py-4" />;
};

const SystemDiagramPage = () => {
  const [selectedDiagram, setSelectedDiagram] = useState<number | null>(null);
  const [exporting, setExporting] = useState(false);
  const modalDiagramRef = useRef<HTMLDivElement>(null);

  const exportToPdf = useCallback(async (index: number) => {
    setExporting(true);
    try {
      // Find the SVG element in the modal diagram
      const container = modalDiagramRef.current;
      if (!container) return;

      const canvas = await html2canvas(container, {
        backgroundColor: "#ffffff",
        scale: 2,
        logging: false,
      });

      const imgData = canvas.toDataURL("image/png");
      const imgWidth = canvas.width;
      const imgHeight = canvas.height;

      // Use landscape if wider than tall
      const orientation = imgWidth > imgHeight ? "landscape" : "portrait";
      const pdf = new jsPDF({ orientation, unit: "px", format: [imgWidth + 80, imgHeight + 120] });

      // Title
      pdf.setFontSize(24);
      pdf.text(DIAGRAMS[index].title, 40, 45);
      pdf.setFontSize(12);
      pdf.setTextColor(120);
      pdf.text(DIAGRAMS[index].description, 40, 65);

      // Diagram image
      pdf.addImage(imgData, "PNG", 40, 85, imgWidth / 2, imgHeight / 2);

      const safeName = DIAGRAMS[index].title.replace(/[^a-zA-Z0-9]/g, "-").toLowerCase();
      pdf.save(`${safeName}.pdf`);
    } catch (e) {
      console.error("PDF export failed:", e);
    } finally {
      setExporting(false);
    }
  }, []);

  return (
    <div className="min-h-screen bg-background text-foreground">
      <header className="border-b border-border bg-card">
        <div className="container mx-auto px-4 py-6">
          <h1 className="text-3xl font-bold">System Architecture Diagrams</h1>
          <p className="text-muted-foreground mt-1">
            UTC Training Platform — technical reference for the development team
          </p>
        </div>
      </header>

      <main className="container mx-auto px-4 py-8 space-y-12">
        {DIAGRAMS.map((d, i) => (
          <section
            key={i}
            className="border border-border rounded-lg bg-card p-6 cursor-pointer hover:border-primary/50 transition-colors group"
            onClick={() => setSelectedDiagram(i)}
          >
            <div className="flex items-start justify-between">
              <div>
                <h2 className="text-xl font-semibold mb-1">{d.title}</h2>
                <p className="text-sm text-muted-foreground mb-4">{d.description}</p>
              </div>
              <Maximize2 className="h-4 w-4 text-muted-foreground group-hover:text-primary shrink-0 mt-1" />
            </div>
            <MermaidDiagram chart={d.mermaid} id={String(i)} />
            <details className="mt-4" onClick={(e) => e.stopPropagation()}>
              <summary className="text-xs text-muted-foreground cursor-pointer hover:text-foreground">
                View Mermaid source
              </summary>
              <pre className="mt-2 p-3 bg-muted rounded text-xs overflow-x-auto whitespace-pre-wrap">
                {d.mermaid}
              </pre>
            </details>
          </section>
        ))}
      </main>

      <Dialog open={selectedDiagram !== null} onOpenChange={() => setSelectedDiagram(null)}>
        <DialogContent className="max-w-[95vw] w-[95vw] max-h-[95vh] overflow-auto">
          {selectedDiagram !== null && (
            <>
              <DialogHeader>
                <div className="flex items-center justify-between pr-8">
                  <div>
                    <DialogTitle>{DIAGRAMS[selectedDiagram].title}</DialogTitle>
                    <p className="text-sm text-muted-foreground">{DIAGRAMS[selectedDiagram].description}</p>
                  </div>
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={exporting}
                    onClick={() => exportToPdf(selectedDiagram)}
                  >
                    <Download className="h-4 w-4 mr-2" />
                    {exporting ? "Exporting…" : "Export PDF"}
                  </Button>
                </div>
              </DialogHeader>
              <div ref={modalDiagramRef} className="overflow-auto py-4 bg-white rounded">
                <MermaidDiagram chart={DIAGRAMS[selectedDiagram].mermaid} id={`modal-${selectedDiagram}`} />
              </div>
              <details>
                <summary className="text-xs text-muted-foreground cursor-pointer hover:text-foreground">
                  View Mermaid source
                </summary>
                <pre className="mt-2 p-3 bg-muted rounded text-xs overflow-x-auto whitespace-pre-wrap">
                  {DIAGRAMS[selectedDiagram].mermaid}
                </pre>
              </details>
            </>
          )}
        </DialogContent>
      </Dialog>

      <footer className="border-t border-border py-6 text-center text-sm text-muted-foreground">
        Generated {new Date().toLocaleDateString()} — UTC Training Platform
      </footer>
    </div>
  );
};

export default SystemDiagramPage;
