import { useState, useEffect, useRef, useMemo } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { BarChart3, Plus, FileDown, Loader2, Search, X, CalendarIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";
import { Badge } from "@/components/ui/badge";
import StatusUpdateCard from "@/components/status-updates/StatusUpdateCard";
import StatusUpdateDialog from "@/components/status-updates/StatusUpdateDialog";
import { StatusUpdatesPdfExport } from "@/components/status-updates/StatusUpdatesPdfExport";
import RecordImportButton from "@/components/RecordImportButton";
import { format, isAfter, isBefore, startOfDay, startOfWeek, startOfMonth, subDays } from "date-fns";

export default function StatusUpdatesPage({ boardAssociationIds }: { boardAssociationIds?: string[] } = {}) {
  const { toast } = useToast();
  const [updates, setUpdates] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [currentUserId, setCurrentUserId] = useState<string | null>(null);
  const [associations, setAssociations] = useState<{ id: string; name: string }[]>([]);
  const [filterAssocId, setFilterAssocId] = useState<string>("all");
  const [search, setSearch] = useState("");
  const [timeframe, setTimeframe] = useState("all");
  const [dateRange, setDateRange] = useState<{ from?: Date; to?: Date } | undefined>(undefined);
  const pdfRef = useRef<any>(null);

  useEffect(() => {
    supabase.auth.getUser().then(({ data }) => {
      setCurrentUserId(data?.user?.id || null);
    });
    supabase.from("associations").select("id, name").eq("status", "active").order("name").then(({ data }) => {
      setAssociations(data || []);
    });
  }, []);

  const isBoardView = !!boardAssociationIds?.length;

  const fetchData = async () => {
    setLoading(true);
    let query = supabase
      .from("status_updates")
      .select("*, associations(name), status_update_votes(*), profiles:created_by(full_name)")
      .order("created_at", { ascending: false });
    if (isBoardView) query = query.in("association_id", boardAssociationIds!);
    if (!isBoardView && filterAssocId !== "all") query = query.eq("association_id", filterAssocId);
    const { data } = await query;
    setUpdates(data || []);
    setLoading(false);
  };

  useEffect(() => { fetchData(); }, [filterAssocId]);

  const filtered = useMemo(() => {
    let result = updates;

    if (search) {
      const term = search.toLowerCase();
      result = result.filter(u =>
        (u.title || "").toLowerCase().includes(term) ||
        (u.content || "").toLowerCase().includes(term) ||
        (u.associations?.name || "").toLowerCase().includes(term)
      );
    }

    if (timeframe !== "all") {
      const now = new Date();
      let cutoff: Date | undefined;
      switch (timeframe) {
        case "today": cutoff = startOfDay(now); break;
        case "week": cutoff = startOfWeek(now); break;
        case "month": cutoff = startOfMonth(now); break;
        case "last30": cutoff = subDays(now, 30); break;
        case "custom":
          if (dateRange?.from) {
            result = result.filter(u => {
              const d = new Date(u.created_at);
              return isAfter(d, dateRange.from!) && (!dateRange.to || isBefore(d, dateRange.to));
            });
          }
          break;
      }
      if (cutoff && timeframe !== "custom") {
        result = result.filter(u => isAfter(new Date(u.created_at), cutoff!));
      }
    }

    return result;
  }, [updates, search, timeframe, dateRange]);

  const hasActiveFilters = search || timeframe !== "all";

  const clearFilters = () => {
    setSearch("");
    setTimeframe("all");
    setDateRange(undefined);
  };

  const openNew = () => { setEditing(null); setDialogOpen(true); };
  const openEdit = (u: any) => { setEditing(u); setDialogOpen(true); };

  const handleExportPdf = async () => {
    if (pdfRef.current && filtered.length > 0) {
      const assocName = filterAssocId !== "all"
        ? associations.find(a => a.id === filterAssocId)?.name || "All Associations"
        : "All Associations";
      await pdfRef.current.generatePdf(filtered, dateRange ? { start: dateRange.from, end: dateRange.to } : null, assocName);
    } else {
      toast({ title: "No data to export" });
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <BarChart3 className="h-6 w-6 text-primary" /> Status Updates
          </h1>
          <p className="text-sm text-muted-foreground mt-1">Track and manage status updates with rich content, images, voting, and comments.</p>
        </div>
        <div className="flex gap-2 flex-wrap">
          <Button variant="outline" className="gap-2" onClick={handleExportPdf} disabled={filtered.length === 0}>
            <FileDown className="h-4 w-4" /> Export PDF
          </Button>
          {!isBoardView && (
            <Button className="gap-2" onClick={openNew}>
              <Plus className="h-4 w-4" /> New Update
            </Button>
          )}
        </div>
      </div>

      {/* Filters */}
      <Card className="border shadow-sm">
        <CardContent className="p-3">
          <div className="flex flex-col lg:flex-row gap-2.5 items-end">
            <div className="flex-1 grid grid-cols-1 sm:grid-cols-4 gap-2.5">
              {/* Search */}
              <div className="sm:col-span-2">
                <label className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground mb-1 block">Search</label>
                <div className="relative">
                  <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground/40" />
                  <Input
                    placeholder="Search title, content, association…"
                    value={search}
                    onChange={e => setSearch(e.target.value)}
                    className="h-8 pl-8 text-[13px] bg-muted/50 border-transparent focus:border-border focus:bg-card"
                  />
                </div>
              </div>

              {/* Association */}
              {!isBoardView && (
                <div>
                  <label className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground mb-1 block">Association</label>
                  <Select value={filterAssocId} onValueChange={setFilterAssocId}>
                    <SelectTrigger className="h-8 text-[13px]">
                      <SelectValue placeholder="All" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Associations</SelectItem>
                      {associations.map((a) => (
                        <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              )}

              {/* Timeframe */}
              <div>
                <label className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground mb-1 block">Timeframe</label>
                <Select value={timeframe} onValueChange={setTimeframe}>
                  <SelectTrigger className="h-8 text-[13px]">
                    <SelectValue placeholder="All Time" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Time</SelectItem>
                    <SelectItem value="today">Today</SelectItem>
                    <SelectItem value="week">This Week</SelectItem>
                    <SelectItem value="month">This Month</SelectItem>
                    <SelectItem value="last30">Last 30 Days</SelectItem>
                    <SelectItem value="custom">Custom Range</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {hasActiveFilters && (
              <Button variant="ghost" size="sm" className="h-8 text-[12px] gap-1 shrink-0" onClick={clearFilters}>
                <X className="w-3 h-3" /> Clear
              </Button>
            )}
          </div>

          {/* Custom date range picker */}
          {timeframe === "custom" && (
            <div className="flex items-center gap-2 mt-2 pt-2 border-t">
              <Popover>
                <PopoverTrigger asChild>
                  <Button variant="outline" size="sm" className="h-8 text-[12px] gap-1.5">
                    <CalendarIcon className="w-3.5 h-3.5" />
                    {dateRange?.from ? format(dateRange.from, "MMM d, yyyy") : "Start date"}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0" align="start">
                  <Calendar mode="single" selected={dateRange?.from} onSelect={(d) => setDateRange(prev => ({ ...prev, from: d || undefined }))} />
                </PopoverContent>
              </Popover>
              <span className="text-xs text-muted-foreground">to</span>
              <Popover>
                <PopoverTrigger asChild>
                  <Button variant="outline" size="sm" className="h-8 text-[12px] gap-1.5">
                    <CalendarIcon className="w-3.5 h-3.5" />
                    {dateRange?.to ? format(dateRange.to, "MMM d, yyyy") : "End date"}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0" align="start">
                  <Calendar mode="single" selected={dateRange?.to} onSelect={(d) => setDateRange(prev => ({ ...prev, to: d || undefined }))} />
                </PopoverContent>
              </Popover>
            </div>
          )}

          {/* Results count */}
          {(hasActiveFilters || filterAssocId !== "all") && (
            <div className="flex items-center gap-2 mt-2">
              <Badge variant="secondary" className="text-[11px]">
                {filtered.length} of {updates.length} updates
              </Badge>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Import button row */}
      {!isBoardView && (
        <div className="flex justify-end">
          <RecordImportButton
            title="Import Status Updates"
            description="Upload a CSV or Excel file with status update records."
            expectedColumns={[
              { key: "title", label: "Title", required: true },
              { key: "content", label: "Content", required: true },
              { key: "association", label: "Association Name", required: true },
            ]}
            onImport={async (rows) => {
              const { data: assocs } = await supabase.from("associations").select("id, name").eq("status", "active");
              const assocMap = new Map((assocs || []).map(a => [a.name.toLowerCase(), a.id]));
              const { data: { user } } = await supabase.auth.getUser();
              const payload = rows.map(r => {
                const assocId = assocMap.get((r.association || "").toLowerCase().trim());
                if (!assocId) throw new Error(`Association not found: "${r.association}"`);
                return {
                  title: r.title,
                  content: r.content,
                  association_id: assocId,
                  created_by: user?.id || null,
                };
              });
              const { error } = await supabase.from("status_updates").insert(payload);
              if (error) throw error;
              toast({ title: `Imported ${rows.length} status updates` });
              fetchData();
            }}
            templateFileName="status_updates_template.xlsx"
          />
        </div>
      )}

      {loading ? (
        <div className="flex justify-center py-12">
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
        </div>
      ) : filtered.length === 0 ? (
        <Card>
          <CardContent className="py-12 text-center text-muted-foreground">
            {hasActiveFilters || filterAssocId !== "all"
              ? "No status updates match your filters."
              : "No status updates yet. Click \"New Update\" to create one."}
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-4">
          {filtered.map((u, i) => (
            <StatusUpdateCard
              key={u.id}
              update={u}
              canManage={!isBoardView}
              onEdit={() => openEdit(u)}
              onDelete={fetchData}
              onRefresh={fetchData}
              index={i}
              currentUserId={currentUserId}
            />
          ))}
        </div>
      )}

      <StatusUpdateDialog
        open={dialogOpen}
        onOpenChange={setDialogOpen}
        update={editing}
        onSuccess={fetchData}
        currentUserId={currentUserId}
      />

      <StatusUpdatesPdfExport ref={pdfRef} />
    </div>
  );
}
