import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Printer, Loader2 } from 'lucide-react';
import { format } from 'date-fns';
import { useToast } from '@/hooks/use-toast';
import QRCode from 'qrcode';

export default function ElectionNoticeGenerator({ election, positions, candidates, voters }) {
  const [generating, setGenerating] = useState(false);
  const { toast } = useToast();

  const generateNotices = async () => {
    setGenerating(true);
    try {
      const votingUrl = `${window.location.origin}/vote/${election.id}`;
      const assocName = election.association?.name || 'Your Association';
      const votingStart = election.voting_start ? format(new Date(election.voting_start), 'MMMM d, yyyy h:mm a') : 'TBD';
      const votingEnd = election.voting_end ? format(new Date(election.voting_end), 'MMMM d, yyyy h:mm a') : 'TBD';

      // Build positions/candidates summary
      const positionsSummary = positions.map(pos => {
        const posCandidates = candidates.filter(c => c.position_id === pos.id);
        return `
          <div style="margin-bottom:12px;">
            <strong style="font-size:13px;">${pos.title}</strong> (${pos.seats_available} seat${pos.seats_available > 1 ? 's' : ''})
            <ul style="margin:4px 0 0 20px;padding:0;">
              ${posCandidates.map(c => `<li style="font-size:12px;margin-bottom:2px;">${c.candidate_name}${c.bio ? ` — <em>${c.bio}</em>` : ''}</li>`).join('')}
              ${posCandidates.length === 0 ? '<li style="font-size:12px;color:#999;">No candidates listed yet</li>' : ''}
            </ul>
          </div>`;
      }).join('');

      // Generate QR codes for each voter
      const voterPages = await Promise.all(voters.map(async (v, idx) => {
        const ownerName = `${v.owner?.first_name || ''} ${v.owner?.last_name || ''}`.trim() || 'Owner';
        const unitLabel = v.unit?.unit_number || v.unit?.address || 'N/A';
        const tokenUrl = v.vote_token ? `${votingUrl}?token=${v.vote_token}` : votingUrl;

        // Generate QR code as data URL
        let qrDataUrl = '';
        try {
          qrDataUrl = await QRCode.toDataURL(tokenUrl, {
            width: 160,
            margin: 1,
            color: { dark: '#1e3a5f', light: '#ffffff' }
          });
        } catch (e) {
          console.error('QR generation failed:', e);
        }

        return `
          <div class="notice-page" style="page-break-after:${idx < voters.length - 1 ? 'always' : 'auto'};">
            <div style="border:2px solid #1e3a5f;border-radius:8px;padding:40px;max-width:680px;margin:0 auto;">
              
              <div style="text-align:center;border-bottom:2px solid #1e3a5f;padding-bottom:16px;margin-bottom:24px;">
                <h1 style="margin:0;font-size:22px;color:#1e3a5f;text-transform:uppercase;letter-spacing:1px;">Official Election Notice</h1>
                <p style="margin:4px 0 0;font-size:14px;color:#475569;">${assocName}</p>
              </div>

              <p style="font-size:13px;margin-bottom:4px;"><strong>To:</strong> ${ownerName}</p>
              <p style="font-size:13px;margin-bottom:4px;"><strong>Unit:</strong> ${unitLabel}</p>
              <p style="font-size:13px;margin-bottom:16px;"><strong>Date:</strong> ${format(new Date(), 'MMMM d, yyyy')}</p>

              <div style="background:#f1f5f9;border-radius:6px;padding:16px;margin-bottom:20px;">
                <h2 style="margin:0 0 8px;font-size:16px;color:#1e3a5f;">${election.title}</h2>
                ${election.description ? `<p style="font-size:12px;color:#475569;margin:0 0 8px;">${election.description}</p>` : ''}
                <p style="font-size:12px;margin:0;"><strong>Voting Opens:</strong> ${votingStart}</p>
                <p style="font-size:12px;margin:0;"><strong>Voting Closes:</strong> ${votingEnd}</p>
              </div>

              ${positions.length > 0 ? `
                <h3 style="font-size:14px;color:#1e3a5f;margin-bottom:8px;">Positions & Candidates</h3>
                ${positionsSummary}
              ` : ''}

              <div style="background:#1e3a5f;color:white;border-radius:6px;padding:20px;margin:20px 0;text-align:center;">
                <h3 style="margin:0 0 4px;font-size:14px;font-weight:bold;">YOUR ACCESS CODE</h3>
                <p style="margin:0 0 12px;font-size:11px;opacity:0.8;">Use this code to cast your ballot online</p>
                <div style="background:white;color:#1e3a5f;display:inline-block;padding:12px 28px;border-radius:6px;font-family:monospace;font-size:32px;font-weight:bold;letter-spacing:0.3em;">
                  ${v.access_code || '------'}
                </div>
              </div>

              <div style="background:#eff6ff;border:1px solid #93c5fd;border-radius:6px;padding:16px;margin:20px 0;">
                <div style="display:flex;gap:16px;align-items:flex-start;">
                  <div style="flex:1;">
                    <h3 style="margin:0 0 8px;font-size:14px;color:#1e3a5f;">How to Vote</h3>
                    <p style="font-size:12px;margin:0 0 6px;"><strong>Option 1 — Scan QR Code:</strong> Use your phone camera to scan the code.</p>
                    <p style="font-size:12px;margin:0 0 6px;"><strong>Option 2 — Visit Website:</strong></p>
                    <ol style="margin:0;padding-left:20px;font-size:12px;line-height:1.8;">
                      <li>Go to <strong>${window.location.origin}/vote/${election.id}</strong></li>
                      <li>Enter your 6-character access code above</li>
                      <li>Review candidates and submit your ballot</li>
                    </ol>
                  </div>
                  ${qrDataUrl ? `
                    <div style="flex-shrink:0;text-align:center;">
                      <img src="${qrDataUrl}" alt="Scan to vote" style="width:130px;height:130px;" />
                      <p style="font-size:9px;color:#475569;margin:4px 0 0;">Scan to Vote</p>
                    </div>
                  ` : ''}
                </div>
              </div>

              <div style="font-size:11px;color:#64748b;border-top:1px solid #e2e8f0;padding-top:12px;margin-top:20px;">
                <p style="margin:0 0 4px;"><strong>Important:</strong> Per Florida Statutes §718.112 / §720.306, electronic voting requires your prior consent. Your ballot is secret — only participation is recorded.</p>
                <p style="margin:0;">You may change your vote at any time before the voting deadline. For questions, contact your association manager.</p>
              </div>

            </div>
          </div>`;
      }));

      const html = `<!DOCTYPE html>
<html><head>
<meta charset="UTF-8">
<title>Election Notices - ${election.title}</title>
<style>
  * { box-sizing: border-box; }
  body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 20px; background: #f8fafc; color: #1e293b; }
  .notice-page { padding: 20px 0; }
  .controls { text-align: center; padding: 16px; background: #e2e8f0; border-radius: 8px; margin-bottom: 24px; }
  .btn { display: inline-block; background: #1e3a5f; color: white; padding: 10px 24px; border-radius: 6px; border: none; cursor: pointer; font-size: 14px; font-weight: 600; margin: 0 8px; }
  .btn:hover { background: #15304f; }
  .btn-outline { background: white; color: #334155; border: 1px solid #cbd5e1; }
  .btn-outline:hover { background: #f8fafc; }
  @media print {
    body { background: white; padding: 0; }
    .controls { display: none !important; }
    .notice-page { padding: 0; }
  }
</style>
</head><body>
<div class="controls">
  <button class="btn" onclick="window.print()">🖨️ Print All Notices (${voters.length})</button>
  <button class="btn btn-outline" onclick="window.close()">Close</button>
</div>
${voterPages.join('')}
</body></html>`;

      const w = window.open('', '_blank');
      w.document.write(html);
      w.document.close();
      toast({ title: 'Notices Generated', description: `${voters.length} voter notice(s) ready to print.` });
    } catch (err) {
      console.error('Notice generation error:', err);
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to generate notices.' });
    } finally {
      setGenerating(false);
    }
  };

  return (
    <Button
      variant="outline" size="sm" className="gap-1 text-xs"
      onClick={generateNotices}
      disabled={generating || voters.length === 0}
    >
      {generating ? <Loader2 className="w-3 h-3 animate-spin" /> : <Printer className="w-3 h-3" />}
      Print Voter Notices
    </Button>
  );
}
