import { useState, useRef, useEffect } from "react";
import { useSearchParams } from "react-router-dom";
import {
  FilePlus, FileText, Save, Printer, Eye, FileDown, Search,
  ChevronDown, AlertTriangle, Plus, Undo2, Redo2,
  Bold, Italic, Underline, Strikethrough, AlignLeft, AlignCenter,
  AlignRight, AlignJustify, List, ListOrdered, IndentDecrease, IndentIncrease,
  Link, Image, Table, Type, Globe, Mail, BookOpen, CreditCard,
  ListChecks, FileCheck, Scale, ShieldAlert, FileWarning, Receipt, BadgeCheck
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useToast } from "@/components/ui/use-toast";
import { generateValidationProof } from "@/lib/generateValidationProof";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";

// Form components
import PublicFormPage from "@/components/forms/PublicFormPage";
import LetterGenerator from "@/components/forms/LetterGenerator";
import { CustomFormBuilder } from "@/components/forms/CustomFormBuilder";
import EnvelopePrintingForm from "@/components/forms/EnvelopePrintingForm";
import CustomLedgerForm from "@/components/forms/CustomLedgerForm";
import PaymentCouponForm from "@/components/forms/PaymentCouponForm";
import MeetingAgendaForm from "@/components/forms/MeetingAgendaForm";
import MeetingMinutesForm from "@/components/forms/MeetingMinutesForm";
import EstoppelForm from "@/components/forms/EstoppelForm";
import LateAssessmentForm from "@/components/forms/LateAssessmentForm";
import NoticeOfIntentToLienForm from "@/components/forms/NoticeOfIntentToLienForm";
import BatchAssessmentForm from "@/components/forms/BatchAssessmentForm";
import InvoiceForm from "@/components/forms/InvoiceForm";
import ViolationNoticeForm from "@/components/forms/ViolationNoticeForm";
import IncidentReportForm from "@/components/forms/IncidentReportForm";
import BallotForm from "@/components/forms/BallotForm";
import BallotEnvelopeForm from "@/components/forms/BallotEnvelopeForm";
import AffidavitOfMailingForm from "@/components/forms/AffidavitOfMailingForm";
import CustomVariablesManager from "@/components/CustomVariablesManager";
import { PdfFormTemplateBuilder } from "@/components/forms/pdf-form-builder/PdfFormTemplateBuilder";

// Document type tabs
const DOCUMENT_TYPES = [
  { id: "custom-forms", label: "Custom Forms", icon: FilePlus },
  { id: "pdf-forms", label: "PDF Form Creator", icon: FileCheck },
  { id: "public", label: "Public", icon: Globe },
  { id: "letters", label: "Letters", icon: FileText },
  { id: "envelopes", label: "Envelopes", icon: Mail },
  { id: "ledger", label: "Ledger", icon: BookOpen },
  { id: "coupons", label: "Coupons", icon: CreditCard },
  { id: "agenda", label: "Agenda", icon: ListChecks },
  { id: "minutes", label: "Minutes", icon: FileText },
  { id: "estoppels", label: "Estoppels", icon: FileCheck },
  { id: "nola", label: "NOLA", icon: AlertTriangle },
  { id: "itl", label: "ITL", icon: Scale },
  
  { id: "batch-notices", label: "Batch Notices", icon: AlertTriangle },
  { id: "invoices", label: "Invoices", icon: Receipt },
  { id: "violations", label: "Violations", icon: ShieldAlert },
  { id: "incidents", label: "Incidents", icon: FileWarning },
  { id: "ballot", label: "Ballot", icon: BadgeCheck },
  { id: "ballot-envelopes", label: "Ballot Envelopes", icon: Mail },
  { id: "affidavit", label: "Affidavit", icon: FileCheck },
  { id: "variables", label: "Custom Variables", icon: Type },
];

// System variables for the sidebar
const SYSTEM_VARIABLES = [
  { key: "clientName", label: "{{clientName}}", description: "Client / Association Name" },
  { key: "ownersNames", label: "{{ownersNames}}", description: "Recipient Full Names (e.g. John & Jane Doe)" },
  { key: "ownerName", label: "{{ownerName}}", description: "Recipient Name (Alias for ownersNames)" },
  { key: "propertyAddress", label: "{{propertyAddress}}", description: "Recipient Property Address" },
  { key: "recipientAddress", label: "{{recipientAddress}}", description: "Recipient Mailing Address" },
  { key: "currentDate", label: "{{currentDate}}", description: "Current Date" },
  { key: "unitId", label: "{{unitId}}", description: "Unit ID / Account Number" },
  { key: "balance", label: "{{balance}}", description: "Current Balance Due" },
  { key: "boardPresident", label: "{{boardPresident}}", description: "Board President Name" },
];

function ToolbarButton({ icon: Icon, label, active = false, onClick }: {
  icon: React.ElementType; label: string; active?: boolean; onClick?: () => void;
}) {
  return (
    <button
      type="button"
      title={label}
      onClick={onClick}
      className={`p-1.5 rounded hover:bg-accent transition-colors ${active ? "bg-accent text-primary" : "text-muted-foreground"}`}
    >
      <Icon className="h-4 w-4" />
    </button>
  );
}

// The custom forms editor (original default tab content)
function CustomFormsEditor() {
  const [activeSubTab, setActiveSubTab] = useState("content");
  const [templateName, setTemplateName] = useState("");
  const [selectedAssociation, setSelectedAssociation] = useState("");
  const [variableSearch, setVariableSearch] = useState("");
  const [editorContent, setEditorContent] = useState("");
  const editorRef = useRef<HTMLDivElement>(null);

  const filteredVariables = SYSTEM_VARIABLES.filter(
    (v) =>
      v.key.toLowerCase().includes(variableSearch.toLowerCase()) ||
      v.description.toLowerCase().includes(variableSearch.toLowerCase())
  );

  const insertVariable = (variable: string) => {
    if (editorRef.current) {
      editorRef.current.focus();
      document.execCommand("insertText", false, variable);
    }
  };

  return (
    <>
      {/* Sub-tabs + Action Buttons */}
      <div className="px-6 pt-3 flex flex-wrap items-center gap-3">
        <Tabs value={activeSubTab} onValueChange={setActiveSubTab} className="flex-shrink-0">
          <TabsList className="h-9 bg-muted/50">
            <TabsTrigger value="content" className="text-xs px-4">Content</TabsTrigger>
            <TabsTrigger value="design" className="text-xs px-4">Design</TabsTrigger>
            <TabsTrigger value="global" className="text-xs px-4">Global</TabsTrigger>
          </TabsList>
        </Tabs>

        <div className="flex items-center gap-2 flex-wrap flex-1 justify-end">
          <Select>
            <SelectTrigger className="w-[140px] h-9 text-xs">
              <Plus className="h-3.5 w-3.5 mr-1" />
              <SelectValue placeholder="Create New" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="blank">Blank Document</SelectItem>
              <SelectItem value="from-template">From Template</SelectItem>
            </SelectContent>
          </Select>

          <Input
            placeholder="Template Name..."
            value={templateName}
            onChange={(e) => setTemplateName(e.target.value)}
            className="w-[160px] h-9 text-xs"
          />

          <Button variant="outline" size="sm" className="gap-1.5 text-xs h-9">
            <Save className="h-3.5 w-3.5" /> Save
          </Button>
          <Button variant="outline" size="sm" className="gap-1.5 text-xs h-9">
            <Printer className="h-3.5 w-3.5" /> Print
          </Button>
          <Button variant="outline" size="sm" className="gap-1.5 text-xs h-9">
            <Eye className="h-3.5 w-3.5" /> Preview
          </Button>
          <Button variant="outline" size="sm" className="gap-1.5 text-xs h-9 text-primary border-primary hover:bg-primary/5">
            <Save className="h-3.5 w-3.5" /> Save to Docs
          </Button>
          <Button size="sm" className="gap-1.5 text-xs h-9">
            <FileDown className="h-3.5 w-3.5" /> Export PDF
          </Button>
        </div>
      </div>

      {/* Main Content: Sidebar + Editor */}
      <div className="flex flex-1 min-h-0 mt-4 px-6 pb-6 gap-4">
        {/* Left Sidebar */}
        <div className="w-[280px] flex-shrink-0 flex flex-col gap-4 overflow-y-auto">
          <div>
            <label className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1.5 block">
              Association / Client
            </label>
            <Select value={selectedAssociation} onValueChange={setSelectedAssociation}>
              <SelectTrigger className="w-full h-9 text-xs">
                <SelectValue placeholder="Select Association" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="assoc-1">Sample HOA Community</SelectItem>
                <SelectItem value="assoc-2">Lakeside Estates</SelectItem>
                <SelectItem value="assoc-3">Parkview Condominiums</SelectItem>
              </SelectContent>
            </Select>
            {!selectedAssociation && (
              <div className="flex items-center gap-1.5 mt-2 text-[11px] text-warning">
                <AlertTriangle className="h-3.5 w-3.5" />
                <span>Select a client to resolve variables</span>
              </div>
            )}
          </div>

          <Separator />

          <div className="flex-1 min-h-0 flex flex-col">
            <label className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1.5 block">
              Variables
            </label>
            <p className="text-[11px] text-muted-foreground mb-2">
              Click a variable to insert it at your cursor position in the document.
            </p>
            <div className="flex items-center gap-1.5 mb-2 text-sm font-medium text-foreground">
              <span className="text-muted-foreground font-mono text-xs">{`{}`}</span>
              Variables Library
            </div>
            <div className="relative mb-3">
              <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
              <Input
                placeholder="Search variables..."
                value={variableSearch}
                onChange={(e) => setVariableSearch(e.target.value)}
                className="pl-8 h-8 text-xs"
              />
            </div>

            <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-2">
              System Variables
            </div>
            <ScrollArea className="flex-1">
              <div className="space-y-0.5 pr-2">
                {filteredVariables.map((v) => (
                  <button
                    key={v.key}
                    onClick={() => insertVariable(v.label)}
                    className="w-full text-left px-2.5 py-2 rounded hover:bg-accent transition-colors border-b border-border/50 last:border-0"
                  >
                    <div className="font-mono text-xs font-semibold text-warning">
                      {v.label}
                    </div>
                    <div className="text-[11px] text-muted-foreground mt-0.5">
                      {v.description}
                    </div>
                  </button>
                ))}
              </div>
            </ScrollArea>
          </div>
        </div>

        {/* Editor Area */}
        <div className="flex-1 flex flex-col min-h-0 border border-border rounded-lg bg-card overflow-hidden">
          <div className="px-6 pt-5 pb-3">
            <h2 className="text-xl font-bold text-foreground">Official Notice</h2>
          </div>

          {!selectedAssociation && (
            <div className="mx-6 mb-3 flex items-center gap-2 px-4 py-3 rounded-md bg-warning/10 border border-warning/30 text-sm">
              <AlertTriangle className="h-4 w-4 text-warning flex-shrink-0" />
              <div>
                <span className="font-medium text-foreground">No Client Selected</span>
                <span className="text-muted-foreground ml-1">— Select a client from the sidebar to resolve variables.</span>
              </div>
            </div>
          )}

          {/* Rich Text Toolbar */}
          <div className="px-4 py-2 border-y border-border bg-muted/30 flex flex-wrap items-center gap-0.5">
            <ToolbarButton icon={Undo2} label="Undo" />
            <ToolbarButton icon={Redo2} label="Redo" />
            <Separator orientation="vertical" className="h-5 mx-1" />

            <Select defaultValue="normal">
              <SelectTrigger className="h-7 w-[90px] text-xs border-border">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="normal">Normal</SelectItem>
                <SelectItem value="h1">Heading 1</SelectItem>
                <SelectItem value="h2">Heading 2</SelectItem>
                <SelectItem value="h3">Heading 3</SelectItem>
              </SelectContent>
            </Select>

            <Select defaultValue="default">
              <SelectTrigger className="h-7 w-[90px] text-xs border-border">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="default">Default</SelectItem>
                <SelectItem value="serif">Serif</SelectItem>
                <SelectItem value="mono">Mono</SelectItem>
              </SelectContent>
            </Select>

            <Select defaultValue="12">
              <SelectTrigger className="h-7 w-[55px] text-xs border-border">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {[10, 11, 12, 14, 16, 18, 20, 24, 28, 32].map((s) => (
                  <SelectItem key={s} value={String(s)}>{s}</SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Separator orientation="vertical" className="h-5 mx-1" />
            <ToolbarButton icon={Bold} label="Bold" />
            <ToolbarButton icon={Italic} label="Italic" />
            <ToolbarButton icon={Underline} label="Underline" />
            <ToolbarButton icon={Strikethrough} label="Strikethrough" />
            <Separator orientation="vertical" className="h-5 mx-1" />
            <ToolbarButton icon={AlignLeft} label="Align Left" />
            <ToolbarButton icon={AlignCenter} label="Align Center" />
            <ToolbarButton icon={List} label="Bullet List" />
            <ToolbarButton icon={ListOrdered} label="Numbered List" />
            <ToolbarButton icon={IndentDecrease} label="Decrease Indent" />
            <ToolbarButton icon={IndentIncrease} label="Increase Indent" />
            <Separator orientation="vertical" className="h-5 mx-1" />
            <ToolbarButton icon={Link} label="Insert Link" />
            <ToolbarButton icon={Image} label="Insert Image" />
            <ToolbarButton icon={Table} label="Insert Table" />
            <ToolbarButton icon={Type} label="Clear Formatting" />
          </div>

          {/* Editable Content Area */}
          <div className="flex-1 overflow-y-auto p-6">
            <div
              ref={editorRef}
              contentEditable
              suppressContentEditableWarning
              className="min-h-[400px] outline-none text-sm text-foreground leading-relaxed focus:outline-none"
              onInput={(e) => setEditorContent((e.target as HTMLDivElement).innerHTML)}
            >
              <p className="text-muted-foreground">Start typing here...</p>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

// Tab content mapping
const TAB_COMPONENTS: Record<string, React.ComponentType> = {
  "custom-forms": CustomFormBuilder,
  "pdf-forms": PdfFormTemplateBuilder,
  "public": PublicFormPage,
  "letters": LetterGenerator,
  "envelopes": EnvelopePrintingForm,
  "ledger": CustomLedgerForm,
  "coupons": PaymentCouponForm,
  "agenda": MeetingAgendaForm,
  "minutes": MeetingMinutesForm,
  "estoppels": EstoppelForm,
  "nola": LateAssessmentForm,
  "itl": NoticeOfIntentToLienForm,
  "late-notices": BatchAssessmentForm,
  
  "batch-notices": BatchAssessmentForm,
  "invoices": InvoiceForm,
  "violations": ViolationNoticeForm,
  "incidents": IncidentReportForm,
  "ballot": BallotForm,
  "ballot-envelopes": BallotEnvelopeForm,
  "affidavit": AffidavitOfMailingForm,
  "variables": CustomVariablesManager,
};

export default function FormsLettersPage() {
  const { toast } = useToast();
  const [searchParams, setSearchParams] = useSearchParams();
  const [activeDocType, setActiveDocType] = useState(searchParams.get("tab") || "custom-forms");
  const [validating, setValidating] = useState(false);
  const [showValidateDialog, setShowValidateDialog] = useState(false);
  const [validateDocName, setValidateDocName] = useState("");

  // Auto-select tab from query params (e.g. from Outstanding Balances)
  useEffect(() => {
    const tab = searchParams.get("tab");
    if (tab && TAB_COMPONENTS[tab]) {
      setActiveDocType(tab);
    }
  }, [searchParams]);

  const ActiveComponent = TAB_COMPONENTS[activeDocType] || CustomFormsEditor;

  const docLabel = DOCUMENT_TYPES.find(d => d.id === activeDocType)?.label || activeDocType;

  const handleValidateClick = () => {
    setValidateDocName("");
    setShowValidateDialog(true);
  };

  const handleValidateConfirm = async () => {
    const title = validateDocName.trim() || docLabel;
    setShowValidateDialog(false);
    setValidating(true);
    try {
      await generateValidationProof({
        documentType: docLabel,
        documentTitle: title,
        documentDate: new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }),
      });
      toast({ title: "Validation certificate generated", description: "PDF certificate with QR code has been downloaded." });
    } catch (err: any) {
      toast({ variant: "destructive", title: "Error generating proof", description: err.message });
    } finally {
      setValidating(false);
    }
  };

  return (
    <div className="flex h-full w-full min-w-0 max-w-full overflow-hidden">
      {/* Left sidebar nav */}
      <div className="w-[200px] shrink-0 border-r bg-card overflow-y-auto">
        <div className="px-4 pt-5 pb-3">
          <h1 className="text-sm font-bold text-foreground">Forms & Letters</h1>
          <p className="text-[11px] text-muted-foreground mt-0.5">Create & manage documents</p>
        </div>
        <nav className="px-2 pb-4 space-y-0.5">
          {DOCUMENT_TYPES.map((dt) => (
            <button
              key={dt.id}
              onClick={() => setActiveDocType(dt.id)}
              className={`w-full flex items-center gap-2 px-3 py-2 text-xs font-medium rounded-md transition-colors ${
                activeDocType === dt.id
                  ? "bg-primary text-primary-foreground"
                  : "text-muted-foreground hover:text-foreground hover:bg-muted"
              }`}
            >
              {dt.icon && <dt.icon className="h-3.5 w-3.5 shrink-0" />}
              <span className="truncate">{dt.label}</span>
            </button>
          ))}
        </nav>

        {/* Validate & Certify button */}
        <div className="px-3 pb-4">
          <Separator className="mb-3" />
          <Button
            variant="outline"
            size="sm"
            className="w-full gap-1.5 text-xs border-emerald-300 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
            onClick={handleValidateClick}
            disabled={validating}
          >
            <BadgeCheck className="h-3.5 w-3.5" />
            {validating ? "Generating..." : "Validate & Certify"}
          </Button>
          <p className="text-[10px] text-muted-foreground mt-1.5 text-center">
            Generate a timestamped certificate with QR verification
          </p>
        </div>
      </div>

      {/* Active Tab Content */}
      <div className="flex-1 min-h-0 min-w-0 overflow-auto flex flex-col">
        <ActiveComponent />
      </div>

      {/* Validate Document Name Dialog */}
      <Dialog open={showValidateDialog} onOpenChange={setShowValidateDialog}>
        <DialogContent className="sm:max-w-[420px]">
          <DialogHeader>
            <DialogTitle>Validate & Certify</DialogTitle>
            <DialogDescription>Enter the name of the document to appear on the validation certificate.</DialogDescription>
          </DialogHeader>
          <div className="space-y-3 py-2">
            <div className="space-y-2">
              <Label>Document Name</Label>
              <Input
                placeholder={`e.g. ${docLabel} - Pine Valley HOA`}
                value={validateDocName}
                onChange={(e) => setValidateDocName(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter') handleValidateConfirm(); }}
                autoFocus
              />
              <p className="text-xs text-muted-foreground">This name will be displayed on the certificate of validation.</p>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowValidateDialog(false)}>Cancel</Button>
            <Button onClick={handleValidateConfirm} disabled={validating}>
              <BadgeCheck className="h-4 w-4 mr-2" />
              Generate Certificate
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
