"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { FOLLOWUP_STATUSES } from "@/lib/leads/constants";
import type { Followup } from "@/lib/types";

export type FollowupRow = Followup & {
  lead?: {
    id: string;
    full_name: string;
    phone: string | null;
    lead_status?: string | null;
  } | null;
  type?: { name: string } | null;
};

const ALL = "__all__";

const STATUS_STYLES: Record<string, string> = {
  pending: "bg-amber-100 text-amber-800",
  done: "bg-green-100 text-green-800",
  missed: "bg-red-100 text-red-800",
};

function fmtTime(t: string | null) {
  if (!t) return "";
  // from_time / to_time come as "HH:MM:SS" — trim to HH:MM
  return t.slice(0, 5);
}

export function FollowupsTable({
  followups,
  showStatusFilter = false,
  showDate = false,
}: {
  followups: FollowupRow[];
  showStatusFilter?: boolean;
  showDate?: boolean;
}) {
  const [status, setStatus] = useState<string>(ALL);

  const filtered = useMemo(() => {
    if (status === ALL) return followups;
    return followups.filter((f) => f.status === status);
  }, [followups, status]);

  return (
    <div className="space-y-4">
      {showStatusFilter && (
        <div className="flex flex-wrap items-center gap-3">
          <Select value={status} onValueChange={setStatus}>
            <SelectTrigger className="h-9 w-44">
              <SelectValue placeholder="All statuses" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value={ALL}>All statuses</SelectItem>
              {FOLLOWUP_STATUSES.map((s) => (
                <SelectItem key={s} value={s}>
                  {s}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      )}

      <Card className="p-0">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-12">No</TableHead>
              <TableHead>Lead</TableHead>
              <TableHead>Phone</TableHead>
              {showDate && <TableHead>Date</TableHead>}
              <TableHead>Time</TableHead>
              <TableHead>Type</TableHead>
              <TableHead>Status</TableHead>
              <TableHead>Notes</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filtered.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={showDate ? 8 : 7}
                  className="py-10 text-center text-muted-foreground"
                >
                  No follow-ups
                </TableCell>
              </TableRow>
            ) : (
              filtered.map((f, i) => {
                const time = [fmtTime(f.from_time), fmtTime(f.to_time)]
                  .filter(Boolean)
                  .join(" – ");
                return (
                  <TableRow key={f.id}>
                    <TableCell className="text-muted-foreground">
                      {i + 1}
                    </TableCell>
                    <TableCell className="font-medium">
                      {f.lead ? (
                        <Link
                          href={`/leads/${f.lead.id}`}
                          className="hover:text-brand-blue hover:underline"
                        >
                          {f.lead.full_name}
                        </Link>
                      ) : (
                        "—"
                      )}
                    </TableCell>
                    <TableCell>{f.lead?.phone ?? "—"}</TableCell>
                    {showDate && (
                      <TableCell>
                        {f.next_date
                          ? new Date(f.next_date).toLocaleDateString()
                          : "—"}
                      </TableCell>
                    )}
                    <TableCell>{time || "—"}</TableCell>
                    <TableCell>{f.type?.name ?? "—"}</TableCell>
                    <TableCell>
                      <Badge
                        className={
                          STATUS_STYLES[f.status] ?? "bg-muted text-foreground"
                        }
                      >
                        {f.status}
                      </Badge>
                    </TableCell>
                    <TableCell className="max-w-xs truncate">
                      {f.notes ?? "—"}
                    </TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </Card>
    </div>
  );
}
