import { useState, useEffect, useMemo } from "react";
import { useSearchParams } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Users } from "lucide-react";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { OwnerUpdateForm } from "@/components/owner-updates/OwnerUpdateForm";
import RecordImportButton from "@/components/RecordImportButton";
import { OwnerUpdatesList } from "@/components/owner-updates/OwnerUpdatesList";
import { OwnerUpdatesFilterBar } from "@/components/owner-updates/OwnerUpdatesFilterBar";
import { startOfDay, startOfWeek, startOfMonth, subDays, isAfter, isBefore } from "date-fns";

const PAGE_SIZE = 20;

export default function OwnerUpdatesPage() {
  const { toast } = useToast();
  const [searchParams] = useSearchParams();
  const [updates, setUpdates] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [associations, setAssociations] = useState([]);
  const [selectedAssociation, setSelectedAssociation] = useState("");
  const [units, setUnits] = useState([]);
  const [page, setPage] = useState(1);

  // Filters
  const [searchTerm, setSearchTerm] = useState("");
  const [timeframe, setTimeframe] = useState("all");
  const [dateRange, setDateRange] = useState(undefined);
  const [selectedTags, setSelectedTags] = useState([]);

  useEffect(() => {
    supabase.from("associations").select("id, name").eq("status", "active").order("name").then(({ data }) => {
      setAssociations(data || []);
      const associationId = searchParams.get("associationId");
      if (associationId) setSelectedAssociation(associationId);
      else if (data?.length === 1) setSelectedAssociation(data[0].id);
    });
  }, [searchParams]);

  useEffect(() => {
    if (!selectedAssociation) { setUnits([]); return; }
    supabase.from("units").select("id, unit_number, address, association_id").eq("association_id", selectedAssociation).order("unit_number").then(({ data }) => setUnits(data || []));
  }, [selectedAssociation]);

  const fetchUpdates = async () => {
    setLoading(true);
    setError(null);
    try {
      let query = supabase.from("owner_updates").select("*, units(id, unit_number, address, owners(id, first_name, last_name, status)), associations(name)").order("posted_at", { ascending: false });
      if (selectedAssociation) query = query.eq("association_id", selectedAssociation);
      const { data, error: err } = await query;
      if (err) throw err;
      setUpdates(data || []);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchUpdates(); }, [selectedAssociation]);

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

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

    if (timeframe !== "all") {
      const now = new Date();
      let cutoff;
      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.posted_at || 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.posted_at || u.created_at), cutoff));
      }
    }

    if (selectedTags.length > 0) {
      result = result.filter(u => {
        const tags = Array.isArray(u.tags) ? u.tags : [];
        return selectedTags.some(st => tags.some(t => t.name === st));
      });
    }

    return result;
  }, [updates, searchTerm, timeframe, dateRange, selectedTags]);

  const totalPages = Math.max(1, Math.ceil(filteredUpdates.length / PAGE_SIZE));
  const paginatedUpdates = filteredUpdates.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

  const availableTags = useMemo(() => {
    const tagSet = new Map();
    updates.forEach(u => {
      if (Array.isArray(u.tags)) u.tags.forEach(t => { if (!tagSet.has(t.name)) tagSet.set(t.name, t); });
    });
    return Array.from(tagSet.values());
  }, [updates]);

  const handleTagClick = (tagName) => {
    setSelectedTags(prev => prev.includes(tagName) ? prev.filter(t => t !== tagName) : [...prev, tagName]);
  };

  return (
    <div className="flex flex-col h-full">
      <div className="pb-0 space-y-4">
        <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"><Users className="h-6 w-6 text-primary" /> Owner Updates</h1>
            <p className="text-sm text-muted-foreground mt-1">Post and manage updates linked to units, violations, and collections.</p>
          </div>
          <div className="flex items-end gap-2">
            <div className="w-full sm:w-64">
              <Label className="text-xs text-muted-foreground mb-1 block">Association</Label>
              <Select value={selectedAssociation} onValueChange={(v) => { setSelectedAssociation(v); setPage(1); }}>
                <SelectTrigger><SelectValue placeholder="Select association" /></SelectTrigger>
                <SelectContent>{associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}</SelectContent>
              </Select>
            </div>
            <RecordImportButton
              title="Import Owner Updates"
              description="Upload a CSV or Excel file with owner update records."
              expectedColumns={[
                { key: "title", label: "Title" },
                { key: "content", label: "Content", required: true },
                { key: "unit_number", label: "Unit Number" },
                { key: "association", label: "Association Name" },
                { key: "tags", label: "Tags (comma-separated)" },
              ]}
              onImport={async (rows) => {
                const assocMap = new Map(associations.map(a => [a.name.toLowerCase(), a.id]));
                const unitMap = new Map(units.map(u => [String(u.unit_number).toLowerCase(), u.id]));
                const payload = rows.map(r => {
                  const assocId = r.association ? assocMap.get(r.association.toLowerCase().trim()) : selectedAssociation;
                  if (!assocId) throw new Error(`Association not found: "${r.association || 'none selected'}"`);
                  const unitId = r.unit_number ? unitMap.get(r.unit_number.toLowerCase().trim()) || null : null;
                  const tags = r.tags ? r.tags.split(",").map(t => ({ name: t.trim(), color: "#6366f1" })) : [];
                  return {
                    title: r.title || null,
                    content: r.content,
                    association_id: assocId,
                    unit_id: unitId,
                    tags,
                    posted_at: new Date().toISOString(),
                  };
                });
                const { error } = await supabase.from("owner_updates").insert(payload);
                if (error) throw error;
                toast({ title: `Imported ${rows.length} owner updates` });
                fetchUpdates();
              }}
              templateFileName="owner_updates_template.xlsx"
            />
          </div>
        </div>

        <OwnerUpdatesFilterBar
          searchTerm={searchTerm} onSearchChange={setSearchTerm}
          timeframe={timeframe} onTimeframeChange={setTimeframe}
          dateRange={dateRange} onDateRangeChange={setDateRange}
          selectedTags={selectedTags} onTagsChange={setSelectedTags}
          availableTags={availableTags}
          onClearFilters={() => { setSearchTerm(""); setTimeframe("all"); setDateRange(undefined); setSelectedTags([]); }}
          totalCount={updates.length} filteredCount={filteredUpdates.length}
        />
      </div>

      <div className="flex-1 flex flex-col lg:flex-row gap-6 p-6 pt-4 min-h-0 overflow-hidden">
        {selectedAssociation && (
          <div className="w-full lg:w-[400px] shrink-0 overflow-y-auto">
            <OwnerUpdateForm units={units} selectedUnitId={searchParams.get("unitId") || undefined} associationId={selectedAssociation} onSuccess={fetchUpdates} />
          </div>
        )}
        <div className="flex-1 min-h-0 border rounded-lg overflow-hidden bg-background">
          <OwnerUpdatesList
            updates={paginatedUpdates} loading={loading} error={error}
            onRefresh={fetchUpdates} onTagClick={handleTagClick} selectedTags={selectedTags}
            page={page} totalPages={totalPages} onPageChange={setPage}
          />
        </div>
      </div>
    </div>
  );
}
