import { useEffect, useState, useCallback } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Save, Loader2, FileDown, Users, Percent, Calculator, MapPin, Clock } from "lucide-react";
import jsPDF from "jspdf";

interface AnnualMeetingTabProps {
  associationId: string;
  associationName: string;
}

const CHECKLIST_SECTIONS = [
  {
    title: "PREPARATION & PLANNING",
    items: [
      "Arrange for meeting location",
      "Establish agenda",
      "Check-in with Board President to:",
      "Confirm meeting agenda",
      "Determine if President, officer, committees and guest speakers will be presenting",
      "Determine meeting chairperson",
      "Determine who is eligible to vote",
      "Evaluate the Board members terms of office and expired terms",
      "Determine time limits for unit owner participation",
      "Review election procedures",
      "Review sign-in procedures",
      "Review quorum requirement",
      "Complete notice of meeting",
      "Complete mailing",
      "Include nomination notices",
      "Include Notices of Intent and Candidate Information Sheet",
      "Include certificate of designated voters",
      "Proxies, ballots and secret ballots",
      "Review last annual meeting draft minutes",
      "Review delinquencies to determine members in good standing",
      "Review current financial and provide copies to Board",
      "Prepare voter registration sign-in sheet",
      "Review policy of how meetings will be conducted",
      "Complete pre-annual meeting touch base",
    ],
  },
  {
    title: "MEETING MATERIALS",
    items: [
      "Annual meeting folder",
      "Affidavit of mailing",
      "Copy of annual meeting notice",
      "Extra meeting agendas",
      "Copies of draft meeting minutes",
      "Copies of current financial",
      "Associations Governing Documents & Amendments",
      "Copy of State Statutes",
      "Robert Rules of Order cheat sheet",
      "Extra blank ballots and ballot box",
      "Extra blank proxies and blank certificates of designated voters",
      "Completed proxies",
      "Voter registration sign-in sheet",
      "Committee sign-up sheet",
      "Nomination Notices",
      "Notice of Intent and Candidate Information Sheets",
      "Additional handouts per Board request",
    ],
  },
  {
    title: "MEETING CHECKLIST",
    items: [
      "Set-up annual meeting",
      "Table for Board",
      "Chairs for owners",
      "Designated area for sign-in",
      "Assign minute taking",
      "Assign inspectors of election",
      "Verify and confirm quorum",
      "Oversee voter registration, sign-in and distribution of ballots",
      "Be prepared for nomination of candidates from the floor",
      "Follow meeting agenda",
      "Follow Roberts Rules of Order",
      "Monitor meeting time",
      "Tally and announce vote results",
      "Schedule organizational meeting",
      "Clean-up after meeting is adjourned",
    ],
  },
  {
    title: "POST MEETING ACTION",
    items: [
      "Complete post-annual meeting touch base",
      "Draft annual meeting minutes and distribute to the board for review",
      "Upload approved annual meeting minutes into Buildium",
      "Scan and save voter registration, proxies, and ballots",
      "Once the Organization Meeting is held, complete the Board of Directors file update",
      "Confirm new board members are added to Buildium",
      "Deliver Quick Start Guide to new Board members with requested Resource Guides",
    ],
  },
];

export default function AnnualMeetingTab({ associationId, associationName }: AnnualMeetingTabProps) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [meetingId, setMeetingId] = useState<string | null>(null);
  const [totalUnits, setTotalUnits] = useState<number>(0);
  const [quorumPercent, setQuorumPercent] = useState<number>(0);
  const [meetingDate, setMeetingDate] = useState("");
  const [meetingTime, setMeetingTime] = useState("");
  const [meetingLocation, setMeetingLocation] = useState("");
  const [notes, setNotes] = useState("");

  const quorumNeeded = Math.ceil((totalUnits * quorumPercent) / 100);

  const fetchMeeting = useCallback(async () => {
    setLoading(true);
    const { data } = await supabase
      .from("annual_meetings")
      .select("*")
      .eq("association_id", associationId)
      .maybeSingle();

    if (data) {
      setMeetingId(data.id);
      setTotalUnits((data as any).total_units || 0);
      setQuorumPercent(Number((data as any).quorum_percent) || 0);
      setMeetingDate((data as any).meeting_date || "");
      setMeetingTime((data as any).meeting_time || "");
      setMeetingLocation((data as any).meeting_location || "");
      setNotes((data as any).notes || "");
    }
    setLoading(false);
  }, [associationId]);

  useEffect(() => { fetchMeeting(); }, [fetchMeeting]);

  const handleSave = async () => {
    setSaving(true);
    const payload = {
      association_id: associationId,
      total_units: totalUnits,
      quorum_percent: quorumPercent,
      quorum_needed: quorumNeeded,
      meeting_date: meetingDate || null,
      meeting_time: meetingTime || null,
      meeting_location: meetingLocation || null,
      notes: notes || null,
    };

    let error;
    if (meetingId) {
      const res = await supabase.from("annual_meetings").update(payload as any).eq("id", meetingId);
      error = res.error;
    } else {
      const res = await supabase.from("annual_meetings").insert(payload as any).select().single();
      error = res.error;
      if (res.data) setMeetingId(res.data.id);
    }

    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "Annual meeting saved" });
    }
    setSaving(false);
  };

  const formatTime12 = (t: string) => {
    if (!t) return "";
    const [h, m] = t.split(":").map(Number);
    const ampm = h >= 12 ? "PM" : "AM";
    const h12 = h % 12 || 12;
    return `${h12}:${m.toString().padStart(2, "0")} ${ampm}`;
  };

  const exportPdf = () => {
    const doc = new jsPDF({ unit: "pt", format: "letter" });
    const pageW = doc.internal.pageSize.getWidth();
    const pageH = doc.internal.pageSize.getHeight();
    const marginL = 50;
    const marginR = 50;
    const contentW = pageW - marginL - marginR;
    let y = 50;

    const checkPage = (needed: number) => {
      if (y + needed > pageH - 50) {
        // page border on current page
        doc.setDrawColor(0);
        doc.setLineWidth(1.5);
        doc.rect(20, 20, pageW - 40, pageH - 40);
        doc.addPage();
        y = 50;
      }
    };

    // Header block with accent line
    doc.setFillColor(30, 58, 95);
    doc.rect(20, 20, pageW - 40, 4, "F");

    y = 55;
    doc.setFont("helvetica", "bold");
    doc.setFontSize(18);
    doc.setTextColor(30, 58, 95);
    doc.text(associationName.toUpperCase(), pageW / 2, y, { align: "center" });
    y += 24;

    doc.setFontSize(14);
    doc.setTextColor(80, 80, 80);
    doc.text("Annual Meeting Checklist", pageW / 2, y, { align: "center" });
    y += 8;

    // Divider
    doc.setDrawColor(30, 58, 95);
    doc.setLineWidth(0.75);
    doc.line(marginL, y, pageW - marginR, y);
    y += 18;

    // Meeting details box
    doc.setFillColor(245, 247, 250);
    doc.setDrawColor(200, 205, 215);
    doc.setLineWidth(0.5);
    const boxH = 70;
    doc.roundedRect(marginL, y - 4, contentW, boxH, 4, 4, "FD");

    doc.setFontSize(10);
    doc.setFont("helvetica", "bold");
    doc.setTextColor(30, 58, 95);
    const col1 = marginL + 12;
    const col2 = marginL + contentW / 2 + 12;
    let detailY = y + 14;

    doc.text("Date:", col1, detailY);
    doc.setFont("helvetica", "normal");
    doc.setTextColor(50, 50, 50);
    doc.text(meetingDate || "TBD", col1 + 60, detailY);

    doc.setFont("helvetica", "bold");
    doc.setTextColor(30, 58, 95);
    doc.text("Time:", col2, detailY);
    doc.setFont("helvetica", "normal");
    doc.setTextColor(50, 50, 50);
    doc.text(formatTime12(meetingTime) || "TBD", col2 + 60, detailY);

    detailY += 18;
    doc.setFont("helvetica", "bold");
    doc.setTextColor(30, 58, 95);
    doc.text("Location:", col1, detailY);
    doc.setFont("helvetica", "normal");
    doc.setTextColor(50, 50, 50);
    doc.text(meetingLocation || "TBD", col1 + 60, detailY);

    detailY += 18;
    doc.setFont("helvetica", "bold");
    doc.setTextColor(30, 58, 95);
    doc.text("Total Units:", col1, detailY);
    doc.setFont("helvetica", "normal");
    doc.setTextColor(50, 50, 50);
    doc.text(String(totalUnits), col1 + 60, detailY);

    doc.setFont("helvetica", "bold");
    doc.setTextColor(30, 58, 95);
    doc.text("Quorum:", col2, detailY);
    doc.setFont("helvetica", "normal");
    doc.setTextColor(50, 50, 50);
    doc.text(`${quorumPercent}% (${quorumNeeded} owners)`, col2 + 60, detailY);

    y += boxH + 16;
    doc.setTextColor(0, 0, 0);

    // Sections
    CHECKLIST_SECTIONS.forEach((section) => {
      checkPage(36);

      // Section header with accent bar
      doc.setFillColor(30, 58, 95);
      doc.rect(marginL, y - 2, 3, 14, "F");
      doc.setFont("helvetica", "bold");
      doc.setFontSize(11);
      doc.setTextColor(30, 58, 95);
      doc.text(section.title, marginL + 10, y + 9);
      y += 20;

      doc.setDrawColor(200, 205, 215);
      doc.setLineWidth(0.5);
      doc.line(marginL, y - 4, marginL + contentW, y - 4);
      y += 4;

      doc.setFont("helvetica", "normal");
      doc.setFontSize(10);
      doc.setTextColor(40, 40, 40);

      section.items.forEach((item) => {
        checkPage(18);
        doc.setDrawColor(150, 150, 150);
        doc.setLineWidth(0.5);
        doc.rect(marginL + 4, y - 7, 8, 8);
        const lines = doc.splitTextToSize(item, contentW - 24);
        doc.text(lines, marginL + 18, y);
        y += lines.length * 13 + 4;
      });

      y += 8;
    });

    // Page border on last page
    doc.setDrawColor(0);
    doc.setLineWidth(1.5);
    doc.rect(20, 20, pageW - 40, pageH - 40);

    // Add page borders to all previous pages
    const totalPages = doc.getNumberOfPages();
    for (let i = 1; i < totalPages; i++) {
      doc.setPage(i);
      doc.setDrawColor(0);
      doc.setLineWidth(1.5);
      doc.rect(20, 20, pageW - 40, pageH - 40);
    }

    doc.save(`${associationName.replace(/[^a-zA-Z0-9]/g, "_")}_Annual_Meeting_Checklist.pdf`);
    toast({ title: "PDF exported" });
  };

  if (loading) {
    return (
      <div className="flex justify-center py-12">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <Card className="border-2 border-primary/20">
        <CardHeader className="border-b bg-muted/30">
          <CardTitle className="text-lg flex items-center gap-2">
            <Users className="h-5 w-5 text-primary" />
            Annual Meeting Configuration
          </CardTitle>
          <CardDescription>Set up meeting details and quorum requirements</CardDescription>
        </CardHeader>
        <CardContent className="pt-6 space-y-5">
          {/* Meeting Details */}
          <div>
            <h4 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3">Meeting Details</h4>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="meeting-date">Date</Label>
                <Input id="meeting-date" type="date" value={meetingDate} onChange={(e) => setMeetingDate(e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label htmlFor="meeting-time" className="flex items-center gap-1.5">
                  <Clock className="h-3.5 w-3.5" /> Time
                </Label>
                <Input id="meeting-time" type="time" value={meetingTime} onChange={(e) => setMeetingTime(e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label htmlFor="meeting-location" className="flex items-center gap-1.5">
                  <MapPin className="h-3.5 w-3.5" /> Location
                </Label>
                <Input id="meeting-location" value={meetingLocation} onChange={(e) => setMeetingLocation(e.target.value)} placeholder="e.g. Community Clubhouse" />
              </div>
            </div>
          </div>

          {/* Quorum */}
          <div>
            <h4 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3">Quorum Requirements</h4>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="total-units" className="flex items-center gap-1.5">
                  <Users className="h-3.5 w-3.5" /> Total Units
                </Label>
                <Input id="total-units" type="number" min={0} value={totalUnits} onChange={(e) => setTotalUnits(Number(e.target.value) || 0)} />
              </div>
              <div className="space-y-2">
                <Label htmlFor="quorum-pct" className="flex items-center gap-1.5">
                  <Percent className="h-3.5 w-3.5" /> Quorum %
                </Label>
                <Input id="quorum-pct" type="number" min={0} max={100} value={quorumPercent} onChange={(e) => setQuorumPercent(Number(e.target.value) || 0)} />
              </div>
              <div className="space-y-2">
                <Label className="flex items-center gap-1.5">
                  <Calculator className="h-3.5 w-3.5" /> Owners Needed for Quorum
                </Label>
                <div className="flex h-10 items-center rounded-md border-2 border-primary/30 bg-primary/5 px-3 text-sm font-bold text-primary">
                  {quorumNeeded}
                </div>
              </div>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="notes">Notes</Label>
            <Input id="notes" value={notes} onChange={(e) => setNotes(e.target.value)} placeholder="Optional notes..." />
          </div>

          <div className="flex gap-2 pt-2 border-t">
            <Button onClick={handleSave} disabled={saving} className="gap-2">
              {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
              Save
            </Button>
            <Button variant="outline" onClick={exportPdf} className="gap-2">
              <FileDown className="h-4 w-4" /> Export PDF Checklist
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Checklist Preview */}
      <Card className="border-2 border-primary/20">
        <CardHeader className="border-b bg-muted/30">
          <CardTitle className="text-lg">Checklist Preview</CardTitle>
          <CardDescription>This checklist will be included in the PDF export</CardDescription>
        </CardHeader>
        <CardContent className="pt-6 space-y-6">
          {CHECKLIST_SECTIONS.map((section) => (
            <div key={section.title}>
              <h3 className="font-semibold text-sm uppercase tracking-wide text-primary border-b-2 border-primary/20 pb-1.5 mb-3 flex items-center gap-2">
                <span className="w-1 h-4 bg-primary rounded-full inline-block" />
                {section.title}
              </h3>
              <ul className="space-y-1.5 pl-1">
                {section.items.map((item, i) => (
                  <li key={i} className="flex items-start gap-2.5 text-sm">
                    <span className="mt-0.5 text-muted-foreground shrink-0">☐</span>
                    <span>{item}</span>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </CardContent>
      </Card>
    </div>
  );
}
