import { useState, useEffect, useCallback } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { format } from "date-fns";
import { Bell, Plus, RefreshCw, Send, Pencil, Trash2 } from "lucide-react";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,
} from "@/components/ui/dialog";
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useAuth } from "@/contexts/AuthContext";
import { useToast } from "@/components/ui/use-toast";

interface Reminder {
  id: string;
  title: string;
  description: string | null;
  due_date: string;
  status: string;
  created_by: string;
  assigned_to: string | null;
  last_notified_at: string | null;
  created_at: string;
}

interface Profile {
  user_id: string;
  email: string | null;
  full_name: string | null;
}

export default function RemindersSection() {
  const { user } = useAuth();
  const [reminders, setReminders] = useState<Reminder[]>([]);
  const [profiles, setProfiles] = useState<Record<string, Profile>>({});
  const [assignableUsers, setAssignableUsers] = useState<Profile[]>([]);
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [tab, setTab] = useState<"all" | "mine">("all");
  const [formData, setFormData] = useState({ title: "", description: "", due_date: "", assigned_to: "" });
  const [running, setRunning] = useState(false);
  const { toast } = useToast();

  const handleRunCheck = async () => {
    try {
      setRunning(true);
      const { data, error } = await supabase.functions.invoke("check-reminder-emails", { body: {} });
      if (error) throw error;
      const processed = (data as any)?.processed ?? 0;
      toast({ title: "Reminder check complete", description: `${processed} reminder${processed === 1 ? "" : "s"} processed.` });
      fetchReminders();
    } catch (err: any) {
      toast({ variant: "destructive", title: "Run Check failed", description: err?.message || "Could not run reminder check." });
    } finally {
      setRunning(false);
    }
  };

  const fetchReminders = useCallback(async () => {
    if (!user) return;
    try {
      setLoading(true);
      let query = supabase
        .from("reminders")
        .select("*")
        .or(`created_by.eq.${user.id},assigned_to.eq.${user.id}`)
        .order("due_date", { ascending: true });

      const { data, error } = await query;
      if (error) throw error;
      setReminders((data as Reminder[]) ?? []);

      const userIds = [...new Set((data || []).map(r => r.assigned_to).filter(Boolean))] as string[];
      if (userIds.length > 0) {
        const { data: profileData } = await supabase
          .from("profiles")
          .select("user_id, email, full_name")
          .in("user_id", userIds);
        const map: Record<string, Profile> = {};
        (profileData || []).forEach(p => { map[p.user_id] = p; });
        setProfiles(map);
      }
    } catch (err) {
      console.error("Error fetching reminders:", err);
    } finally {
      setLoading(false);
    }
  }, [user]);

  const fetchAssignableUsers = useCallback(async () => {
    const { data: roleRows, error: roleError } = await supabase
      .from("user_roles")
      .select("user_id")
      .in("role", ["admin", "staff"]);

    if (roleError) {
      console.error("Error fetching reminder assignees:", roleError);
      return;
    }

    const userIds = [...new Set((roleRows || []).map((row) => row.user_id).filter(Boolean))];
    if (userIds.length === 0) {
      setAssignableUsers([]);
      return;
    }

    const { data: profileData, error: profileError } = await supabase
      .from("profiles")
      .select("user_id, email, full_name")
      .in("user_id", userIds)
      .order("full_name");

    if (profileError) {
      console.error("Error fetching assignee profiles:", profileError);
      return;
    }

    const staffProfiles = (profileData as Profile[] | null) ?? [];
    setAssignableUsers(staffProfiles);
    setProfiles((prev) => {
      const next = { ...prev };
      staffProfiles.forEach((profile) => { next[profile.user_id] = profile; });
      return next;
    });
  }, []);

  useEffect(() => {
    if (user) {
      fetchReminders();
      fetchAssignableUsers();
    }
  }, [user, fetchReminders, fetchAssignableUsers]);

  const filtered = tab === "mine"
    ? reminders.filter(r => r.assigned_to === user?.id)
    : reminders;

  const handleSave = async () => {
    if (!formData.title || !formData.due_date) {
      toast({ variant: "destructive", title: "Title and Due Date required" });
      return;
    }
    try {
      const payload: any = {
        title: formData.title,
        description: formData.description || null,
        due_date: formData.due_date,
        assigned_to: formData.assigned_to || null,
      };
      if (editingId) {
        const { error } = await supabase.from("reminders").update(payload).eq("id", editingId);
        if (error) throw error;
      } else {
        const { error } = await supabase.from("reminders").insert([{ ...payload, status: "pending", created_by: user!.id }]);
        if (error) throw error;
      }
      toast({ title: editingId ? "Reminder updated" : "Reminder created" });
      setModalOpen(false);
      fetchReminders();
    } catch (err: any) {
      toast({ variant: "destructive", title: "Error saving reminder", description: err.message });
    }
  };

  const handleDelete = async (id: string) => {
    try {
      const { error } = await supabase.from("reminders").delete().eq("id", id);
      if (error) throw error;
      fetchReminders();
      toast({ title: "Reminder deleted" });
    } catch {
      toast({ variant: "destructive", title: "Error deleting reminder" });
    }
  };

  const openModal = (reminder?: Reminder | null) => {
    if (reminder) {
      setEditingId(reminder.id);
      setFormData({
        title: reminder.title,
        description: reminder.description || "",
        due_date: new Date(reminder.due_date).toISOString().split("T")[0],
        assigned_to: reminder.assigned_to || "",
      });
    } else {
      setEditingId(null);
      setFormData({ title: "", description: "", due_date: "", assigned_to: "" });
    }
    setModalOpen(true);
  };

  const statusBadge = (status: string) => {
    switch (status) {
      case "completed":
        return <Badge className="bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100">Completed</Badge>;
      case "pending":
        return <Badge className="bg-amber-100 text-amber-700 border-amber-200 hover:bg-amber-100">Pending</Badge>;
      default:
        return <Badge variant="secondary">{status}</Badge>;
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-start justify-between">
        <div className="flex items-center gap-3">
          <Bell className="w-8 h-8 text-primary" />
          <div>
            <h1 className="text-2xl font-bold text-foreground">Reminders</h1>
            <p className="text-sm text-muted-foreground">Manage tasks and trigger automated email notifications.</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={handleRunCheck} disabled={running}>
            <Send className="w-4 h-4 mr-1.5" /> {running ? "Running..." : "Run Check"}
          </Button>
          <Button variant="ghost" size="icon" className="h-9 w-9" onClick={fetchReminders}>
            <RefreshCw className="w-4 h-4" />
          </Button>
          <Button size="sm" onClick={() => openModal()}>
            <Plus className="w-4 h-4 mr-1.5" /> New Reminder
          </Button>
        </div>
      </div>

      {/* Table Card */}
      <div className="bg-card border rounded-lg">
        <div className="p-5 border-b">
          <h2 className="text-lg font-semibold text-foreground">Reminder List</h2>
          <p className="text-sm text-muted-foreground mt-1">
            Emails are automatically sent for items due within 24 hours, provided they haven't been notified recently.
          </p>
        </div>

        {/* Tabs */}
        <div className="px-5 pt-4">
          <div className="inline-flex rounded-md border bg-muted/50 p-0.5">
            <button
              onClick={() => setTab("all")}
              className={`px-4 py-1.5 text-sm font-medium rounded-md transition-colors ${
                tab === "all" ? "bg-background shadow-sm text-foreground" : "text-muted-foreground hover:text-foreground"
              }`}
            >
              All Reminders
            </button>
            <button
              onClick={() => setTab("mine")}
              className={`px-4 py-1.5 text-sm font-medium rounded-md transition-colors ${
                tab === "mine" ? "bg-background shadow-sm text-foreground" : "text-muted-foreground hover:text-foreground"
              }`}
            >
              My Reminders
            </button>
          </div>
        </div>

        {/* Table */}
        <div className="p-5">
          {loading ? (
            <div className="text-center py-8 text-muted-foreground">Loading reminders...</div>
          ) : filtered.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">No reminders found.</div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[120px]">Status</TableHead>
                  <TableHead>Title</TableHead>
                  <TableHead className="w-[100px]">Due Date</TableHead>
                  <TableHead>Assigned To</TableHead>
                  <TableHead className="w-[120px]">Last Notified</TableHead>
                  <TableHead className="w-[100px] text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filtered.map((rem) => {
                  const profile = rem.assigned_to ? profiles[rem.assigned_to] : null;
                  return (
                    <TableRow key={rem.id}>
                      <TableCell>{statusBadge(rem.status)}</TableCell>
                      <TableCell>
                        <div className="font-semibold text-foreground">{rem.title}</div>
                        {rem.description && (
                          <div className="text-xs text-muted-foreground truncate max-w-[300px]">{rem.description}</div>
                        )}
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground">
                        {format(new Date(rem.due_date), "MMM d, yyyy")}
                      </TableCell>
                      <TableCell>
                        {profile?.email ? (
                          <Badge variant="outline" className="font-normal">{profile.email}</Badge>
                        ) : (
                          <span className="text-xs text-muted-foreground">—</span>
                        )}
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground">
                        {rem.last_notified_at
                          ? format(new Date(rem.last_notified_at), "MMM d, h:mm a")
                          : "Never"}
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-1">
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8 text-primary hover:text-primary"
                            onClick={() => openModal(rem)}
                          >
                            <Pencil className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8 text-destructive hover:text-destructive"
                            onClick={() => handleDelete(rem.id)}
                          >
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          )}
        </div>
      </div>

      {/* Modal */}
      <Dialog open={modalOpen} onOpenChange={setModalOpen}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>{editingId ? "Edit Reminder" : "New Reminder"}</DialogTitle>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="space-y-2">
              <Label>Title</Label>
              <Input
                value={formData.title}
                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                placeholder="What needs to be done?"
              />
            </div>
            <div className="space-y-2">
              <Label>Description (Optional)</Label>
              <Textarea
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="Additional details..."
                rows={3}
              />
            </div>
            <div className="space-y-2">
              <Label>Due Date</Label>
              <Input
                type="date"
                value={formData.due_date}
                onChange={(e) => setFormData({ ...formData, due_date: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label>Assigned To</Label>
              <Select
                value={formData.assigned_to}
                onValueChange={(value) => setFormData({ ...formData, assigned_to: value })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select staff or admin" />
                </SelectTrigger>
                <SelectContent>
                  {assignableUsers.map((profile) => (
                    <SelectItem key={profile.user_id} value={profile.user_id}>
                      {profile.full_name || profile.email || profile.user_id}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setModalOpen(false)}>Cancel</Button>
            <Button onClick={handleSave}>Save Reminder</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
