import React, { useState, useRef } from 'react';
import { CalendarClock, AlertCircle, RefreshCcw, Loader2, ChevronLeft, ChevronRight, FileDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { OwnerUpdateCard } from './OwnerUpdateCard';
import { OwnerUpdateDialog } from './OwnerUpdateDialog';
import { cn } from '@/lib/utils';
import { jsPDF } from 'jspdf';
import autoTable from 'jspdf-autotable';
import { format } from 'date-fns';

export function OwnerUpdatesList({ updates, loading, error, onRefresh, onTagClick, className, selectedTags = [], page, totalPages, onPageChange }) {
  const [editingUpdate, setEditingUpdate] = useState(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);

  const handleEdit = (update) => { setEditingUpdate(update); setIsDialogOpen(true); };

  const handleExportPdf = () => {
    const doc = new jsPDF({ orientation: 'landscape', unit: 'pt', format: 'letter' });
    const marginLeft = 43, marginRight = 43, marginTop = 34;
    const pageWidth = doc.internal.pageSize.getWidth();
    const pageHeight = doc.internal.pageSize.getHeight();
    let currentY = marginTop;

    doc.setFontSize(18); doc.setTextColor(33, 37, 41); doc.setFont("helvetica", "bold");
    doc.text("Owner Updates Report", marginLeft, currentY + 14);
    doc.setFontSize(11); doc.setTextColor(108, 117, 125); doc.setFont("helvetica", "normal");
    doc.text(`Generated: ${format(new Date(), 'MMM dd, yyyy')}`, pageWidth - marginRight, currentY + 14, { align: 'right' });
    currentY += 50;

    const tableBody = updates.map(item => {
      const dateStr = item.posted_at ? format(new Date(item.posted_at), 'MMM dd, yyyy') : 'N/A';
      const unit = item.units?.unit_number || 'N/A';
      const address = item.units?.address || '';
      const activeOwners = (item.units?.owners || []).filter(o => o.status !== 'archived');
      const owners = activeOwners.map(o => [o.first_name, o.last_name].filter(Boolean).join(' ')).join(', ') || 'N/A';
      let type = 'General';
      if (item.violation_ids?.length > 0) type = 'Violation';
      if (item.collection_ids?.length > 0) type = 'Collection';
      const content = (item.content || '').replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/\s+/g, ' ').trim().substring(0, 200);
      return [dateStr, unit, address, owners, type, content];
    });

    autoTable(doc, {
      startY: currentY,
      head: [['Date', 'Unit', 'Address', 'Owner(s)', 'Type', 'Details']],
      body: tableBody,
      theme: 'grid',
      styles: { font: 'helvetica', fontSize: 9, cellPadding: 6, textColor: 30, valign: 'top', overflow: 'linebreak' },
      headStyles: { fillColor: [71, 85, 105], textColor: 255, fontSize: 10, fontStyle: 'bold' },
      alternateRowStyles: { fillColor: [248, 250, 252] },
      columnStyles: { 0: { cellWidth: 70 }, 1: { cellWidth: 50 }, 2: { cellWidth: 100 }, 3: { cellWidth: 100 }, 4: { cellWidth: 65 } },
      margin: { left: marginLeft, right: marginRight, top: marginTop, bottom: 34 },
      didDrawPage: () => {
        doc.setFontSize(9); doc.setTextColor(150);
        doc.text(`Page ${doc.internal.getNumberOfPages()}`, pageWidth - marginRight, pageHeight - 20, { align: 'right' });
      }
    });
    doc.save(`Owner_Updates_${format(new Date(), 'yyyy-MM-dd')}.pdf`);
  };

  if (error) {
    return (
      <div className={cn("p-4", className)}>
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>Error Loading Updates</AlertTitle>
          <AlertDescription className="mt-2 flex flex-col gap-3 items-start">
            <p>{error}</p>
            <Button variant="outline" size="sm" onClick={onRefresh}><RefreshCcw className="w-4 h-4 mr-2" /> Retry</Button>
          </AlertDescription>
        </Alert>
      </div>
    );
  }

  if (loading && (!updates || updates.length === 0)) {
    return (
      <div className={cn("flex flex-col items-center justify-center h-full text-muted-foreground space-y-4", className)}>
        <Loader2 className="w-8 h-8 animate-spin text-primary" /><p>Loading updates...</p>
      </div>
    );
  }

  if (!updates || updates.length === 0) {
    return (
      <div className={cn("flex flex-col items-center justify-center h-full border border-dashed rounded-lg bg-muted/20 m-4", className)}>
        <div className="p-4 bg-background rounded-full mb-3 shadow-sm"><CalendarClock className="w-8 h-8 text-muted-foreground/50" /></div>
        <p className="text-muted-foreground font-medium">No updates found</p>
        <p className="text-muted-foreground/70 text-sm mt-1">Try adjusting your filters or search criteria.</p>
      </div>
    );
  }

  return (
    <div className={cn("flex flex-col h-full overflow-hidden relative", className)}>
      <div className="flex justify-end items-center px-4 py-2 border-b bg-background/50 backdrop-blur-sm sticky top-0 z-10 shrink-0">
        <Button variant="outline" size="sm" onClick={handleExportPdf} className="gap-1.5">
          <FileDown className="w-3.5 h-3.5" /> Export PDF
        </Button>
      </div>

      {loading && (
        <div className="absolute inset-0 bg-background/60 z-20 flex items-center justify-center backdrop-blur-[1px]">
          <Loader2 className="w-8 h-8 animate-spin text-primary" />
        </div>
      )}

      <div className="flex-1 overflow-y-auto min-h-0">
        <div className="p-4 space-y-4 pb-6">
          {updates.map(update => (
            <OwnerUpdateCard key={update.id} update={update} onEdit={handleEdit} onDeleteSuccess={onRefresh} onTagClick={onTagClick} selectedTags={selectedTags} />
          ))}
        </div>
      </div>

      {totalPages > 1 && (
        <div className="shrink-0 border-t bg-background p-3 flex items-center justify-between">
          <p className="text-sm text-muted-foreground">Page <span className="font-medium text-foreground">{page}</span> of <span className="font-medium text-foreground">{totalPages}</span></p>
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={() => onPageChange(page - 1)} disabled={page <= 1 || loading}><ChevronLeft className="w-4 h-4 mr-1" /> Prev</Button>
            <Button variant="outline" size="sm" onClick={() => onPageChange(page + 1)} disabled={page >= totalPages || loading}>Next <ChevronRight className="w-4 h-4 ml-1" /></Button>
          </div>
        </div>
      )}

      <OwnerUpdateDialog open={isDialogOpen} onOpenChange={setIsDialogOpen} update={editingUpdate} onSuccess={onRefresh} />
    </div>
  );
}
