import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { toast } from "sonner";

export const Route = createFileRoute("/admin/contact")({ component: ContactAdmin });

type Msg = {
  id: string;
  name: string;
  email: string;
  phone: string | null;
  message: string;
  status: "new" | "in_progress" | "replied" | "closed";
  admin_reply: string | null;
  created_at: string;
};

const STATUSES: Msg["status"][] = ["new", "in_progress", "replied", "closed"];

function ContactAdmin() {
  const [rows, setRows] = useState<Msg[]>([]);

  const load = async () => {
    const { data, error } = await supabase.from("contact_submissions").select("*").order("created_at", { ascending: false });
    if (error) toast.error(error.message);
    else setRows((data ?? []) as Msg[]);
  };
  useEffect(() => { load(); }, []);

  const update = async (id: string, patch: Partial<Msg>) => {
    const { error } = await supabase.from("contact_submissions").update(patch).eq("id", id);
    if (error) return toast.error(error.message);
    setRows((rs) => rs.map((r) => (r.id === id ? { ...r, ...patch } : r)));
    toast.success("Saved");
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Customer messages</h1>
        <p className="text-sm text-muted-foreground">Contact form submissions.</p>
      </div>
      <div className="grid gap-3">
        {rows.length === 0 && <p className="text-sm text-muted-foreground">No messages.</p>}
        {rows.map((m) => (
          <Card key={m.id} className="glass">
            <CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0">
              <div>
                <div className="font-semibold">{m.name}</div>
                <div className="text-xs text-muted-foreground">{m.email}{m.phone ? ` · ${m.phone}` : ""}</div>
                <div className="text-xs text-muted-foreground">{new Date(m.created_at).toLocaleString()}</div>
              </div>
              <select
                value={m.status}
                onChange={(e) => update(m.id, { status: e.target.value as Msg["status"] })}
                className="rounded-md border bg-background px-2 py-1 text-xs capitalize"
              >
                {STATUSES.map((s) => <option key={s}>{s}</option>)}
              </select>
            </CardHeader>
            <CardContent className="space-y-2">
              <p className="text-sm">{m.message}</p>
              <ReplyEditor value={m.admin_reply ?? ""} onSave={(v) => update(m.id, { admin_reply: v, status: "replied" })} />
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}

function ReplyEditor({ value, onSave }: { value: string; onSave: (v: string) => void }) {
  const [v, setV] = useState(value);
  useEffect(() => setV(value), [value]);
  return (
    <div className="space-y-2">
      <Textarea placeholder="Internal reply / notes" value={v} onChange={(e) => setV(e.target.value)} rows={2} />
      <Button size="sm" onClick={() => onSave(v)}>Save reply</Button>
    </div>
  );
}