import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Loader2, FileText, Calendar as CalendarIcon, Download, RefreshCw, AlertTriangle, X } from 'lucide-react';
import { format, startOfMonth, endOfMonth, subMonths, isAfter, differenceInDays, isValid } from 'date-fns';
import { useToast } from '@/hooks/use-toast';
import { useAuth } from '@/contexts/AuthContext';
import { supabase } from '@/integrations/supabase/client';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Calendar } from '@/components/ui/calendar';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import { Alert, AlertDescription } from '@/components/ui/alert';

export default function MonthEndReportDialog({ open, onOpenChange, onSuccess }) {
  const { user } = useAuth();
  const { toast } = useToast();

  const now = new Date();
  const [dateRange, setDateRange] = useState({
    start: startOfMonth(now),
    end: endOfMonth(now)
  });
  const [selectedMonth, setSelectedMonth] = useState('current');
  const [isManualDate, setIsManualDate] = useState(false);
  const [dateError, setDateError] = useState(null);

  const [selections, setSelections] = useState({
    status: true,
    owner: true,
    violations: true,
    collections: true,
    estoppels: true,
    callLogs: true
  });

  const [selectedAssociationId, setSelectedAssociationId] = useState(null);
  const [associations, setAssociations] = useState([]);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('config');

  useEffect(() => {
    if (open) {
      setLoading(false);
      fetchAssociations();
      handleMonthChange('current');
      setActiveTab('config');
    }
  }, [open]);

  const validateDates = (start, end) => {
    if (!isValid(start) || !isValid(end)) return "Invalid date selection.";
    if (isAfter(start, end)) return "Start date cannot be after end date.";
    if (differenceInDays(end, start) > 366) return "Date range cannot exceed one year.";
    return null;
  };

  const handleManualDateChange = (type, date) => {
    if (!date) return;
    const newRange = { ...dateRange, [type]: date };
    const error = validateDates(newRange.start, newRange.end);
    setDateRange(newRange);
    setIsManualDate(true);
    setDateError(error);
    if (selectedMonth !== 'custom') setSelectedMonth('custom');
  };

  const handleMonthChange = (val) => {
    setSelectedMonth(val);
    if (val === 'custom') { setIsManualDate(true); return; }
    setIsManualDate(false);
    setDateError(null);
    const now = new Date();
    if (val === 'current') {
      setDateRange({ start: startOfMonth(now), end: endOfMonth(now) });
    } else {
      const last = subMonths(now, 1);
      setDateRange({ start: startOfMonth(last), end: endOfMonth(last) });
    }
  };

  const fetchAssociations = async () => {
    const { data } = await supabase.from('associations').select('id, name').eq('status', 'active').order('name');
    setAssociations(data || []);
    if (data && data.length > 0 && !selectedAssociationId) {
      setSelectedAssociationId(data[0].id);
    }
  };

  const handleGenerate = async () => {
    if (!selectedAssociationId) {
      toast({ variant: "destructive", title: "Error", description: "Please select an association." });
      return;
    }
    if (dateError) {
      toast({ variant: "destructive", title: "Invalid Dates", description: dateError });
      return;
    }

    setLoading(true);
    try {
      // Placeholder for actual report generation logic
      toast({ title: "Report Generation", description: "Month-end report generation requires additional report generator components." });
      if (onSuccess) onSuccess();
    } catch (error) {
      console.error("Generation error:", error);
      toast({ variant: "destructive", title: "Generation Failed", description: error.message || "Failed to generate report." });
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    if (loading) {
      if (window.confirm("Report generation is in progress. Close anyway?")) {
        setLoading(false);
        onOpenChange(false);
      }
    } else {
      onOpenChange(false);
    }
  };

  const DatePicker = ({ date, onSelect, label }) => (
    <div className="flex flex-col gap-1">
      <Label className="text-xs text-muted-foreground">{label}</Label>
      <Popover modal={true}>
        <PopoverTrigger asChild>
          <Button variant="outline" className={cn("w-full justify-start text-left font-normal h-9", !date && "text-muted-foreground")}>
            <CalendarIcon className="mr-2 h-4 w-4" />
            {date ? format(date, "MM/dd/yyyy") : <span>Pick a date</span>}
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto p-0 z-[9999]" align="start">
          <Calendar mode="single" selected={date} onSelect={onSelect} initialFocus disabled={(d) => isAfter(d, new Date())} />
        </PopoverContent>
      </Popover>
    </div>
  );

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent 
        className="sm:max-w-[950px] gap-0 p-0 overflow-hidden max-h-[90vh] flex flex-col z-[60]"
        onPointerDownOutside={(e) => { if (loading) e.preventDefault(); }}
      >
        <DialogHeader className="px-6 py-4 border-b shrink-0 flex flex-row items-center justify-between space-y-0">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-primary/10 rounded-lg">
              <FileText className="w-5 h-5 text-primary" />
            </div>
            <div className="flex flex-col gap-1">
              <DialogTitle className="text-lg leading-none">Generate Month-End Report</DialogTitle>
              <DialogDescription className="text-sm">Compile monthly activity into a professional PDF.</DialogDescription>
            </div>
          </div>
          <Button variant="ghost" size="icon" className="h-8 w-8 text-muted-foreground hover:text-foreground rounded-full" onClick={handleClose} type="button">
            <X className="w-5 h-5" />
          </Button>
        </DialogHeader>

        <div className="flex-1 overflow-hidden min-h-[300px]">
          <Tabs value={activeTab} onValueChange={setActiveTab} className="h-full flex flex-col">
            <div className="px-6 pt-4 border-b bg-muted/30">
              <TabsList className="w-full justify-start">
                <TabsTrigger value="config">Report Settings</TabsTrigger>
              </TabsList>
            </div>

            <TabsContent value="config" className="flex-1 overflow-hidden m-0">
              <div className="p-6 space-y-6 overflow-y-auto h-full pb-20">
                <div className="space-y-3">
                  <Label>Association</Label>
                  <Select value={selectedAssociationId || ''} onValueChange={setSelectedAssociationId}>
                    <SelectTrigger><SelectValue placeholder="Select Association" /></SelectTrigger>
                    <SelectContent>
                      {associations.map(c => <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>)}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-3">
                  <Label className="flex justify-between items-center">
                    Report Period
                    {isManualDate && (
                      <span className="text-xs font-medium text-amber-600 bg-amber-50 px-2 py-0.5 rounded-full border border-amber-200">Custom Range</span>
                    )}
                  </Label>
                  <Select value={selectedMonth} onValueChange={handleMonthChange}>
                    <SelectTrigger>
                      <CalendarIcon className="w-4 h-4 mr-2 text-muted-foreground" />
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="current">Current Month ({format(now, 'MMM')})</SelectItem>
                      <SelectItem value="last">Last Month ({format(subMonths(now, 1), 'MMM')})</SelectItem>
                      <SelectItem value="custom">Custom Date Range</SelectItem>
                    </SelectContent>
                  </Select>
                  
                  <div className={cn("grid grid-cols-2 gap-4 pt-2 transition-all", isManualDate ? "opacity-100" : "opacity-80")}>
                    <DatePicker label="Start Date" date={dateRange.start} onSelect={(d) => handleManualDateChange('start', d)} />
                    <DatePicker label="End Date" date={dateRange.end} onSelect={(d) => handleManualDateChange('end', d)} />
                  </div>

                  {dateError && (
                    <Alert variant="destructive" className="py-2">
                      <AlertTriangle className="h-4 w-4" />
                      <AlertDescription>{dateError}</AlertDescription>
                    </Alert>
                  )}

                  {isManualDate && !dateError && (
                    <div className="flex justify-end">
                      <Button variant="ghost" size="sm" onClick={() => handleMonthChange('current')} className="text-xs h-7">
                        <RefreshCw className="w-3 h-3 mr-1" /> Reset to Month
                      </Button>
                    </div>
                  )}
                </div>

                <div className="space-y-4">
                  <Label>Included Standard Sections</Label>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    {[
                      { id: 'status', label: 'Status Updates' },
                      { id: 'owner', label: 'Owner Reports' },
                      { id: 'violations', label: 'Violations Report' },
                      { id: 'collections', label: 'Collections' },
                      { id: 'estoppels', label: 'Estoppels Report' },
                      { id: 'callLogs', label: 'Call Logs' },
                    ].map((item) => (
                      <div key={item.id} className="flex items-center space-x-2 border p-3 rounded-md hover:bg-muted transition-colors">
                        <Checkbox 
                          id={item.id} 
                          checked={selections[item.id]}
                          onCheckedChange={(c) => setSelections(prev => ({ ...prev, [item.id]: !!c }))}
                        />
                        <Label htmlFor={item.id} className="cursor-pointer flex-1 font-normal text-sm">{item.label}</Label>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </TabsContent>
          </Tabs>
        </div>

        <DialogFooter className="px-6 py-4 border-t bg-muted/30 flex items-center justify-between sm:justify-between shrink-0">
          <div className="text-sm text-muted-foreground italic flex items-center gap-2">
            {loading && <span className="text-xs text-primary animate-pulse">Generating...</span>}
          </div>
          <div className="flex gap-2">
            <Button variant="outline" size="sm" onClick={handleClose} type="button">Cancel</Button>
            <Button size="sm" onClick={handleGenerate} disabled={loading || !!dateError}>
              {loading ? <Loader2 className="w-3 h-3 mr-2 animate-spin" /> : <Download className="w-3 h-3 mr-2" />}
              {loading ? 'Generating...' : 'Generate Report'}
            </Button>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
