import { useEffect, useState, useMemo } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { useToast } from "@/hooks/use-toast";
import { format } from "date-fns";
import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";
import {
  Plus, Download, Search, Filter, Trash2,
  UserPlus, UserMinus, Mail, Phone, AlertTriangle,
  DollarSign, FileText, Send, Clock, Tag, CalendarDays
} from "lucide-react";

const EVENT_TYPES = [
  { value: "move_in", label: "Move In", icon: UserPlus, color: "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400" },
  { value: "move_out", label: "Move Out", icon: UserMinus, color: "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400" },
  { value: "collection", label: "Collection", icon: DollarSign, color: "bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-400" },
  { value: "mail_sent", label: "Mail Sent", icon: Send, color: "bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400" },
  { value: "email_sent", label: "Email Sent", icon: Mail, color: "bg-indigo-100 text-indigo-800 dark:bg-indigo-900/30 dark:text-indigo-400" },
  { value: "phone_call", label: "Phone Call", icon: Phone, color: "bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400" },
  { value: "violation", label: "Violation", icon: AlertTriangle, color: "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400" },
  { value: "document", label: "Document", icon: FileText, color: "bg-cyan-100 text-cyan-800 dark:bg-cyan-900/30 dark:text-cyan-400" },
  { value: "note", label: "Note", icon: FileText, color: "bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-400" },
  { value: "general", label: "General", icon: Clock, color: "bg-muted text-muted-foreground" },
];

const TAG_SUGGESTIONS = ["urgent", "legal", "board", "maintenance", "financial", "follow-up", "resolved", "pending"];

interface Props {
  unitId: string;
  associationId: string;
}

export default function UnitTimelineTab({ unitId, associationId }: Props) {
  const { toast } = useToast();
  const [events, setEvents] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [typeFilter, setTypeFilter] = useState("all");
  const [tagFilter, setTagFilter] = useState("all");
  const [dialogOpen, setDialogOpen] = useState(false);

  // Form state
  const [formType, setFormType] = useState("general");
  const [formTitle, setFormTitle] = useState("");
  const [formDesc, setFormDesc] = useState("");
  const [formTags, setFormTags] = useState<string[]>([]);
  const [formTagInput, setFormTagInput] = useState("");
  const [saving, setSaving] = useState(false);

  const fetchEvents = async () => {
    setLoading(true);
    // 1) Native timeline events
    const { data: rows, error } = await supabase
      .from("unit_timeline_events")
      .select("*")
      .eq("unit_id", unitId)
      .order("created_at", { ascending: false });
    if (error) console.error(error);

    // 2) Pull owner emails for this unit, then fold matching email_history rows in
    const { data: owners } = await supabase
      .from("owners")
      .select("email")
      .eq("unit_id", unitId);
    const emails = Array.from(
      new Set((owners || []).map((o: any) => (o.email || "").trim().toLowerCase()).filter(Boolean))
    );

    let emailEvents: any[] = [];
    if (emails.length > 0) {
      const { data: hist } = await supabase
        .from("email_history")
        .select("id, subject, body_text, recipient_email, sender_email, sent_at, created_at, status")
        .in("recipient_email", emails)
        .order("sent_at", { ascending: false })
        .limit(500);
      emailEvents = (hist || []).map((h: any) => ({
        id: `email-${h.id}`,
        unit_id: unitId,
        association_id: associationId,
        event_type: "email_sent",
        title: h.subject || "(no subject)",
        description: `To: ${h.recipient_email}${h.sender_email ? `  •  From: ${h.sender_email}` : ""}${h.status ? `  •  ${h.status}` : ""}`,
        event_tag: [],
        created_at: h.sent_at || h.created_at,
        _readonly: true,
      }));
    }

    const merged = [...(rows || []), ...emailEvents].sort(
      (a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
    );
    setEvents(merged);
    setLoading(false);
  };

  useEffect(() => { fetchEvents(); }, [unitId]);

  const allTags = useMemo(() => {
    const s = new Set<string>();
    events.forEach(e => (e.event_tag || []).forEach((t: string) => s.add(t)));
    return Array.from(s).sort();
  }, [events]);

  const filtered = useMemo(() => {
    return events.filter(e => {
      if (typeFilter !== "all" && e.event_type !== typeFilter) return false;
      if (tagFilter !== "all" && !(e.event_tag || []).includes(tagFilter)) return false;
      if (search) {
        const q = search.toLowerCase();
        if (!e.title?.toLowerCase().includes(q) && !e.description?.toLowerCase().includes(q)) return false;
      }
      return true;
    });
  }, [events, typeFilter, tagFilter, search]);

  const handleAdd = async () => {
    if (!formTitle.trim()) { toast({ variant: "destructive", title: "Title is required" }); return; }
    setSaving(true);
    const { data: sess } = await supabase.auth.getSession();
    const { error } = await supabase.from("unit_timeline_events").insert({
      unit_id: unitId,
      association_id: associationId,
      event_type: formType,
      title: formTitle.trim(),
      description: formDesc.trim() || null,
      event_tag: formTags,
      created_by: sess?.session?.user?.id || null,
    });
    if (error) {
      toast({ variant: "destructive", title: "Error", description: error.message });
    } else {
      toast({ title: "Event added" });
      setFormTitle(""); setFormDesc(""); setFormTags([]); setFormType("general"); setFormTagInput("");
      setDialogOpen(false);
      fetchEvents();
    }
    setSaving(false);
  };

  const handleDelete = async (id: string) => {
    const { error } = await supabase.from("unit_timeline_events").delete().eq("id", id);
    if (!error) { setEvents(prev => prev.filter(e => e.id !== id)); toast({ title: "Deleted" }); }
  };

  const addTag = (tag: string) => {
    const t = tag.trim().toLowerCase();
    if (t && !formTags.includes(t)) setFormTags([...formTags, t]);
    setFormTagInput("");
  };

  const exportPDF = () => {
    const doc = new jsPDF();
    doc.setFontSize(16);
    doc.text("Unit Timeline Report", 14, 18);
    doc.setFontSize(9);
    doc.setTextColor(120);
    doc.text(`Exported ${format(new Date(), "MMM d, yyyy h:mm a")} • ${filtered.length} events`, 14, 25);
    doc.setTextColor(0);

    autoTable(doc, {
      startY: 30,
      head: [["Date", "Type", "Title", "Description", "Tags"]],
      body: filtered.map(e => [
        format(new Date(e.created_at), "MMM d, yyyy h:mm a"),
        EVENT_TYPES.find(t => t.value === e.event_type)?.label || e.event_type,
        e.title,
        e.description || "—",
        (e.event_tag || []).join(", ") || "—",
      ]),
      styles: { fontSize: 8, cellPadding: 3 },
      headStyles: { fillColor: [37, 99, 235] },
      columnStyles: { 0: { cellWidth: 35 }, 1: { cellWidth: 22 }, 3: { cellWidth: 55 } },
    });

    doc.save("unit-timeline.pdf");
  };

  const getTypeInfo = (type: string) => EVENT_TYPES.find(t => t.value === type) || EVENT_TYPES[EVENT_TYPES.length - 1];

  return (
    <div className="space-y-4">
      {/* Toolbar */}
      <div className="flex flex-wrap items-center gap-2">
        <div className="relative flex-1 min-w-[200px]">
          <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
          <Input placeholder="Search events…" value={search} onChange={e => setSearch(e.target.value)} className="pl-9 h-9" />
        </div>
        <Select value={typeFilter} onValueChange={setTypeFilter}>
          <SelectTrigger className="w-[150px] h-9"><Filter className="h-3.5 w-3.5 mr-1.5" /><SelectValue /></SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Types</SelectItem>
            {EVENT_TYPES.map(t => <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>)}
          </SelectContent>
        </Select>
        <Select value={tagFilter} onValueChange={setTagFilter}>
          <SelectTrigger className="w-[140px] h-9"><Tag className="h-3.5 w-3.5 mr-1.5" /><SelectValue /></SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Tags</SelectItem>
            {allTags.map(t => <SelectItem key={t} value={t}>{t}</SelectItem>)}
          </SelectContent>
        </Select>
        <Button variant="outline" size="sm" className="h-9 gap-1.5" onClick={exportPDF} disabled={filtered.length === 0}>
          <Download className="h-3.5 w-3.5" /> Export PDF
        </Button>
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogTrigger asChild>
            <Button size="sm" className="h-9 gap-1.5"><Plus className="h-3.5 w-3.5" /> Add Event</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader><DialogTitle>Add Timeline Event</DialogTitle></DialogHeader>
            <div className="space-y-3">
              <Select value={formType} onValueChange={setFormType}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  {EVENT_TYPES.map(t => <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>)}
                </SelectContent>
              </Select>
              <Input placeholder="Event title *" value={formTitle} onChange={e => setFormTitle(e.target.value)} />
              <Textarea placeholder="Description (optional)" value={formDesc} onChange={e => setFormDesc(e.target.value)} rows={3} />
              <div>
                <label className="text-xs font-medium text-muted-foreground mb-1 block">Tags</label>
                <div className="flex flex-wrap gap-1.5 mb-2">
                  {formTags.map(t => (
                    <Badge key={t} variant="secondary" className="cursor-pointer text-xs" onClick={() => setFormTags(formTags.filter(x => x !== t))}>
                      {t} ×
                    </Badge>
                  ))}
                </div>
                <div className="flex gap-2">
                  <Input
                    placeholder="Add tag…"
                    value={formTagInput}
                    onChange={e => setFormTagInput(e.target.value)}
                    onKeyDown={e => { if (e.key === "Enter") { e.preventDefault(); addTag(formTagInput); } }}
                    className="h-8 text-sm"
                  />
                </div>
                <div className="flex flex-wrap gap-1 mt-2">
                  {TAG_SUGGESTIONS.filter(t => !formTags.includes(t)).map(t => (
                    <Badge key={t} variant="outline" className="cursor-pointer text-[10px] hover:bg-accent" onClick={() => addTag(t)}>{t}</Badge>
                  ))}
                </div>
              </div>
              <Button className="w-full" onClick={handleAdd} disabled={saving}>{saving ? "Saving…" : "Add Event"}</Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {/* Timeline */}
      {loading ? (
        <div className="flex justify-center py-12"><div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" /></div>
      ) : filtered.length === 0 ? (
        <div className="text-center py-12 text-muted-foreground">
          <Clock className="h-10 w-10 mx-auto mb-2 opacity-40" />
          <p className="text-sm">No timeline events yet</p>
        </div>
      ) : (
        <div className="relative pl-6 border-l-2 border-border space-y-0">
          {filtered.map((ev, i) => {
            const info = getTypeInfo(ev.event_type);
            const Icon = info.icon;
            return (
              <div key={ev.id} className="relative pb-6 last:pb-0 group">
                {/* Dot */}
                <div className="absolute -left-[25px] top-1 w-4 h-4 rounded-full border-2 border-background bg-primary flex items-center justify-center">
                  <div className="w-2 h-2 rounded-full bg-background" />
                </div>

                <div className="ml-4 rounded-lg border border-border bg-card p-3 hover:shadow-sm transition-shadow">
                  <div className="flex items-start justify-between gap-2">
                    <div className="flex items-center gap-2 flex-wrap">
                      <Badge className={`text-[10px] px-1.5 py-0 ${info.color} border-0`}>
                        <Icon className="h-3 w-3 mr-1" />{info.label}
                      </Badge>
                      <span className="font-medium text-sm text-foreground">{ev.title}</span>
                    </div>
                    <div className="flex items-center gap-1.5 shrink-0">
                      <span className="text-[11px] text-muted-foreground flex items-center gap-1">
                        <CalendarDays className="h-3 w-3" />
                        {format(new Date(ev.created_at), "MMM d, yyyy h:mm a")}
                      </span>
                      {!ev._readonly && (
                        <Button variant="ghost" size="icon" className="h-6 w-6 opacity-0 group-hover:opacity-100" onClick={() => handleDelete(ev.id)}>
                          <Trash2 className="h-3 w-3 text-destructive" />
                        </Button>
                      )}
                    </div>
                  </div>
                  {ev.description && <p className="text-xs text-muted-foreground mt-1.5 whitespace-pre-wrap">{ev.description}</p>}
                  {(ev.event_tag || []).length > 0 && (
                    <div className="flex flex-wrap gap-1 mt-2">
                      {ev.event_tag.map((t: string) => (
                        <Badge key={t} variant="outline" className="text-[10px] px-1.5 py-0">{t}</Badge>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
