
import React, { useState } from 'react';
import { ChevronDown, ChevronRight, FileText, AlertCircle, CheckCircle, Clock } from 'lucide-react';
import { ViolationReportPdfExport } from './ViolationReportPdfExport';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { formatDateSafe } from '@/lib/dateUtils';
import { cn } from '@/lib/utils';

export function ViolationSummaryReport({ violations, onExport, dateRange }) {
  const uniqueClients = [...new Set(violations?.map(v => v.clients?.name).filter(Boolean))];
  const clientName = uniqueClients.length === 1 
    ? uniqueClients[0] 
    : (uniqueClients.length > 1 ? "Multiple Associations" : "Homeowners Association");
    
  const generationDate = new Date().toLocaleDateString();

  return (
    <div className="space-y-6 max-w-5xl mx-auto">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 print:hidden bg-white p-4 rounded-lg border shadow-sm">
        <div>
          <h2 className="text-lg font-bold text-slate-900">Violation Summary Report</h2>
          <div className="flex gap-2 items-center text-sm text-slate-500">
             <span>{violations?.length || 0} Records Found</span>
             <span>•</span>
             <span>{clientName}</span>
          </div>
          {dateRange && (dateRange.start || dateRange.end) && (
            <p className="text-xs text-slate-400 mt-1">
              Date Filter: {dateRange.start ? formatDateSafe(dateRange.start) : 'Start'} - {dateRange.end ? formatDateSafe(dateRange.end) : 'Present'}
            </p>
          )}
        </div>
        <ViolationReportPdfExport 
             violations={violations} 
             clientName={clientName} 
             dateRange={dateRange}
             buttonVariant="default"
             buttonClassName="bg-slate-900 text-white hover:bg-slate-800 shadow-md"
        />
      </div>

      <div className="bg-white shadow-sm border border-slate-200 rounded-lg min-h-[11in] w-full mx-auto print:shadow-none print:border-none print:w-full overflow-hidden">
        <div className="bg-slate-900 text-white px-8 py-6 print:bg-slate-900 print:text-white">
          <h1 className="text-2xl font-bold">Violation Summary Report</h1>
          <div className="flex justify-between items-end mt-2">
             <div className="text-slate-300 font-medium">{clientName}</div>
             <div className="text-right">
                <div className="text-xs text-slate-400">Generated: {generationDate}</div>
                {dateRange && (dateRange.start || dateRange.end) && (
                   <div className="text-xs text-slate-400">
                      Range: {dateRange.start ? formatDateSafe(dateRange.start) : 'Start'} to {dateRange.end ? formatDateSafe(dateRange.end) : 'Present'}
                   </div>
                )}
             </div>
          </div>
        </div>

        <div className="p-6 md:p-8 bg-slate-50/50 min-h-[500px]">
          {(!violations || violations.length === 0) ? (
             <div className="flex flex-col items-center justify-center py-20 text-slate-400 border-2 border-dashed border-slate-200 rounded-lg">
                <FileText className="w-12 h-12 mb-4 opacity-50" />
                <p className="text-lg font-medium">No violations found</p>
                <p className="text-sm">Try adjusting your filters.</p>
             </div>
          ) : (
             <div className="grid grid-cols-1 gap-6">
                {violations.map((violation, index) => (
                   <ViolationReportCard key={violation.id || index} violation={violation} />
                ))}
             </div>
          )}
        </div>
      </div>
    </div>
  );
}

function ViolationReportCard({ violation }) {
  const [isOpen, setIsOpen] = useState(true);

  const getStatusColor = (status) => {
      switch((status || '').toLowerCase()) {
          case 'open': return 'bg-red-100 text-red-700 border-red-200';
          case 'resolved': return 'bg-green-100 text-green-700 border-green-200';
          case 'closed': return 'bg-slate-100 text-slate-700 border-slate-200';
          default: return 'bg-blue-100 text-blue-700 border-blue-200';
      }
  };

  const statusColor = getStatusColor(violation.status);
  
  const ownerName = violation.allOwnerNames || violation.property_owners?.owner_name || `${violation.owners?.first_name || ''} ${violation.owners?.last_name || ''}`.trim() || 'Unknown Owner';
  const propertyAddress = violation.property_owners?.property_address || violation.owners?.property_address || violation.address || 'Unknown Address';

  let article = violation.article;
  let section = violation.section;
  let citation = violation.citation;
  let requested_action = violation.requested_action; // Remedy
  let action = violation.action; // HOA Action
  let previousStatus = violation.previous_status;

  if (Array.isArray(violation.notice_history) && violation.notice_history.length > 0) {
      const sortedHistory = [...violation.notice_history].sort((a, b) => new Date(b.date || 0) - new Date(a.date || 0));
      const latest = sortedHistory[0];

      if (!article) article = latest.article || latest.article_section;
      if (!section) section = latest.section;
      if (!citation) citation = latest.citation;
      if (!requested_action) requested_action = latest.requested_action;
      if (!action) action = latest.action;
      
      if (!previousStatus && sortedHistory.length > 1) {
          previousStatus = sortedHistory[1].status;
      }
  }

  const displayArticle = article || 'N/A';
  const displaySection = section || 'N/A';
  const displayCitation = citation || 'N/A';
  const displayReqAction = requested_action || 'N/A';
  const displayAction = action || 'N/A';
  const displayPrevStatus = previousStatus || '-';

  return (
    <Card className="border-slate-200 shadow-sm break-inside-avoid overflow-hidden hover:shadow-md transition-shadow">
       <div 
         className="w-full bg-white px-6 py-4 flex flex-col md:flex-row md:items-center justify-between gap-4 cursor-pointer border-b border-slate-100"
         onClick={() => setIsOpen(!isOpen)}
       >
         <div className="flex items-start gap-4">
             <div className="mt-1">
                {isOpen ? <ChevronDown className="w-5 h-5 text-slate-400" /> : <ChevronRight className="w-5 h-5 text-slate-400" />}
             </div>
             <div>
                <h3 className="font-bold text-slate-900 text-base">{propertyAddress}</h3>
                <p className="text-sm text-slate-500 font-medium">VIOLATION DETAILS</p>
             </div>
         </div>
         
         <div className="flex items-center gap-3 pl-9 md:pl-0">
             <Badge variant="outline" className={cn("capitalize px-3 py-1", statusColor)}>
                 {violation.status || 'Open'}
             </Badge>
             <span className="text-xs text-slate-400 font-medium bg-slate-50 px-2 py-1 rounded">
                Due: {formatDateSafe(violation.due_date)}
             </span>
         </div>
       </div>

       {isOpen && (
         <div className="p-6 bg-slate-50/30">
            <div className="grid grid-cols-12 gap-y-4 gap-x-8 text-sm">
                
                <div className="col-span-12 md:col-span-3 font-bold text-slate-900">Property Address</div>
                <div className="col-span-12 md:col-span-9 text-slate-700">{propertyAddress}</div>

                <div className="col-span-12 md:col-span-3 font-bold text-slate-900">Owner</div>
                <div className="col-span-12 md:col-span-9 text-slate-700">{ownerName}</div>

                <div className="col-span-12 md:col-span-3 font-bold text-slate-900">Violation Type</div>
                <div className="col-span-12 md:col-span-9 text-slate-700">{violation.violation_type || '-'}</div>

                <div className="col-span-12 md:col-span-3 font-bold text-slate-900">Article / Section</div>
                <div className="col-span-12 md:col-span-9 text-slate-700 flex gap-4">
                   <span><span className="text-slate-400 text-xs uppercase mr-1">Art.</span>{displayArticle}</span>
                   <span><span className="text-slate-400 text-xs uppercase mr-1">Sec.</span>{displaySection}</span>
                </div>

                <div className="col-span-12 md:col-span-3 font-bold text-slate-900">Citation</div>
                <div className="col-span-12 md:col-span-9 text-slate-700 whitespace-pre-wrap">{displayCitation}</div>

                <div className="col-span-12 md:col-span-3 font-bold text-slate-900">Requested Action</div>
                <div className="col-span-12 md:col-span-9 text-slate-700 whitespace-pre-wrap">{displayReqAction}</div>
                
                <div className="col-span-12 md:col-span-3 font-bold text-slate-900">Action (HOA)</div>
                <div className="col-span-12 md:col-span-9 text-slate-700 whitespace-pre-wrap">{displayAction}</div>

                <div className="col-span-12 h-px bg-slate-200 my-2"></div>

                <div className="col-span-12 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 pt-2">
                    <div>
                        <span className="block text-[10px] uppercase font-bold text-slate-400 mb-1">Previous Status</span>
                        <div className="flex items-center gap-2 text-slate-600">
                             <Clock className="w-3.5 h-3.5" />
                             {displayPrevStatus}
                        </div>
                    </div>
                    <div>
                        <span className="block text-[10px] uppercase font-bold text-slate-400 mb-1">Current Status</span>
                        <div className="flex items-center gap-2 font-semibold text-slate-800 capitalize">
                             {violation.status === 'resolved' ? <CheckCircle className="w-3.5 h-3.5 text-green-500" /> : <AlertCircle className="w-3.5 h-3.5 text-red-500" />}
                             {violation.status || 'Open'}
                        </div>
                    </div>
                    <div>
                        <span className="block text-[10px] uppercase font-bold text-slate-400 mb-1">Violation Date</span>
                        <div className="text-slate-700">{formatDateSafe(violation.violation_date)}</div>
                    </div>
                    <div>
                        <span className="block text-[10px] uppercase font-bold text-slate-400 mb-1">Due Date</span>
                        <div className="text-slate-700">{formatDateSafe(violation.due_date)}</div>
                    </div>
                </div>

                {violation.photo_url && (
                    <div className="col-span-12 mt-4">
                        <span className="block text-[10px] uppercase font-bold text-slate-400 mb-2">Photo Evidence</span>
                        <div className="relative group overflow-hidden rounded-md border border-slate-200 bg-white w-full max-w-sm aspect-video flex items-center justify-center">
                             <img 
                                src={violation.photo_url} 
                                alt="Violation" 
                                className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" 
                                loading="lazy"
                             />
                        </div>
                    </div>
                )}
            </div>
         </div>
       )}
    </Card>
  );
}
