import Link from "next/link";
import { notFound } from "next/navigation";
import { getLeadFormOptions } from "@/lib/leads/queries";
import { LEAD_STATUS_STYLES } from "@/lib/leads/constants";
import { PageHeader } from "@/components/layout/page-header";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import {
  Card,
  CardHeader,
  CardTitle,
  CardContent,
} from "@/components/ui/card";
import {
  Tabs,
  TabsList,
  TabsTrigger,
  TabsContent,
} from "@/components/ui/tabs";
import {
  StatusChanger,
  AddNoteForm,
  AddFollowupForm,
  CompleteFollowupButton,
  AssignmentEditor,
} from "./lead-detail-client";
import { DeleteLeadDialog } from "../delete-lead-dialog";

function fmtDateTime(iso: string | null): string {
  if (!iso) return "—";
  return new Date(iso).toLocaleString("en-IN", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function fmtDate(d: string | null): string {
  if (!d) return "—";
  return new Date(d).toLocaleDateString("en-IN", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

function InfoRow({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="flex items-start justify-between gap-4 py-1.5 text-sm">
      <span className="text-muted-foreground">{label}</span>
      <span className="text-right font-medium">{value || "—"}</span>
    </div>
  );
}

type TimelineEvent = {
  key: string;
  at: string;
  kind: "created" | "note" | "followup";
  title: string;
  body?: string | null;
};

import { executeGraphQL } from "@/lib/graphql/client";

const GET_LEAD_DETAIL_QUERY = `
  query GetLeadDetail($id: UUID!) {
    leadsCollection(filter: { id: { eq: $id } }) {
      edges {
        node {
          id
          full_name
          email
          phone
          alternate_contact
          country
          city
          preferred_country
          lead_status
          created_at
          source: lead_sources { name }
          inquiry: inquiries { name }
          interested_course: interested_courses { name }
          lead_notesCollection(orderBy: [{ created_at: DescNullsLast }]) {
            edges {
              node {
                id
                body
                created_at
              }
            }
          }
          followupsCollection(orderBy: [{ created_at: DescNullsLast }]) {
            edges {
              node {
                id
                next_date
                from_time
                to_time
                status
                notes
                outcome
                created_at
                completed_at
                type: followup_types { name }
              }
            }
          }
          lead_assignmentsCollection {
            edges {
              node {
                user_id
                user: users { full_name }
              }
            }
          }
        }
      }
    }
  }
`;

export default async function LeadDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;

  const [{ data, errors }, options] = await Promise.all([
    executeGraphQL(GET_LEAD_DETAIL_QUERY, { id }),
    getLeadFormOptions(),
  ]);

  if (errors) {
    console.error("GraphQL errors fetching lead detail:", errors);
  }

  const rawLead = data?.leadsCollection?.edges?.[0]?.node;
  if (!rawLead) notFound();

  const lead = {
    ...rawLead,
    source: rawLead.source ? { name: rawLead.source.name } : null,
    inquiry: rawLead.inquiry ? { name: rawLead.inquiry.name } : null,
    interested_course: rawLead.interested_course ? { name: rawLead.interested_course.name } : null,
  };

  const notes = (rawLead.lead_notesCollection?.edges?.map((e: any) => e.node) ?? []) as {
    id: string;
    body: string;
    created_at: string;
  }[];

  const followups = (rawLead.followupsCollection?.edges?.map((e: any) => ({
    ...e.node,
    type: e.node.type ? { name: e.node.type.name } : null,
  })) ?? []) as {
    id: string;
    next_date: string | null;
    from_time: string | null;
    to_time: string | null;
    status: string;
    notes: string | null;
    outcome: string | null;
    created_at: string;
    completed_at: string | null;
    type: { name: string } | { name: string }[] | null;
  }[];

  const assignments = (rawLead.lead_assignmentsCollection?.edges?.map((e: any) => ({
    user_id: e.node.user_id,
    user: e.node.user ? { full_name: e.node.user.full_name } : null,
  })) ?? []) as {
    user_id: string;
    user: { full_name: string } | { full_name: string }[] | null;
  }[];

  const oneName = (
    rel: { name: string } | { name: string }[] | null | undefined,
  ): string => {
    if (!rel) return "";
    const r = Array.isArray(rel) ? rel[0] : rel;
    return r?.name ?? "";
  };

  const assignedUserIds = assignments.map((a) => a.user_id);
  const assignedNames = assignments.map((a) => {
    const u = Array.isArray(a.user) ? a.user[0] : a.user;
    return u?.full_name ?? "Unknown";
  });

  // Merged activity timeline, newest first.
  const timeline: TimelineEvent[] = [
    {
      key: `created-${lead.id}`,
      at: lead.created_at,
      kind: "created" as const,
      title: "Lead created",
    },
    ...notes.map((n) => ({
      key: `note-${n.id}`,
      at: n.created_at,
      kind: "note" as const,
      title: "Note added",
      body: n.body,
    })),
    ...followups.map((f) => ({
      key: `fu-${f.id}`,
      at: f.created_at,
      kind: "followup" as const,
      title: `Follow-up scheduled${
        oneName(f.type) ? ` · ${oneName(f.type)}` : ""
      }`,
      body: [
        f.next_date ? `Due ${fmtDate(f.next_date)}` : null,
        f.status ? `(${f.status})` : null,
        f.notes,
      ]
        .filter(Boolean)
        .join(" "),
    })),
  ].sort((a, b) => new Date(b.at).getTime() - new Date(a.at).getTime());

  const statusStyle =
    LEAD_STATUS_STYLES[lead.lead_status] ?? "bg-gray-100 text-gray-800";

  return (
    <div>
      <PageHeader
        title={lead.full_name}
        breadcrumb="Leads / Detail"
        action={
          <div className="flex items-center gap-2">
            <StatusChanger leadId={lead.id} current={lead.lead_status} />
            <Button asChild variant="outline">
              <Link href={`/leads/${lead.id}/edit`}>Edit</Link>
            </Button>
            <DeleteLeadDialog leadId={lead.id} leadName={lead.full_name} redirectToLeads />
          </div>
        }
      />

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        {/* Left: lead information */}
        <Card className="lg:col-span-1">
          <CardHeader>
            <CardTitle>Lead Information</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="mb-3 flex items-center justify-between">
              <span className="text-sm text-muted-foreground">Status</span>
              <Badge className={statusStyle}>{lead.lead_status}</Badge>
            </div>
            <Separator className="my-2" />
            <InfoRow label="Email" value={lead.email} />
            <InfoRow label="Phone" value={lead.phone} />
            <InfoRow label="Alternate" value={lead.alternate_contact} />
            <Separator className="my-2" />
            <InfoRow label="Country" value={lead.country} />
            <InfoRow label="City" value={lead.city} />
            <InfoRow
              label="Preferred country"
              value={lead.preferred_country}
            />
            <Separator className="my-2" />
            <InfoRow label="Source" value={oneName(lead.source)} />
            <InfoRow label="Inquiry" value={oneName(lead.inquiry)} />
            <InfoRow
              label="Interested course"
              value={oneName(lead.interested_course)}
            />
            <Separator className="my-2" />
            <InfoRow label="Created" value={fmtDateTime(lead.created_at)} />
          </CardContent>
        </Card>

        {/* Right: tabs */}
        <Card className="lg:col-span-2">
          <CardContent className="pt-6">
            <Tabs defaultValue="activity">
              <TabsList>
                <TabsTrigger value="activity">Activity</TabsTrigger>
                <TabsTrigger value="followups">Follow-ups</TabsTrigger>
                <TabsTrigger value="notes">Notes</TabsTrigger>
                <TabsTrigger value="assignment">Assignment</TabsTrigger>
              </TabsList>

              {/* Activity timeline */}
              <TabsContent value="activity" className="mt-4">
                {timeline.length === 0 ? (
                  <p className="text-sm text-muted-foreground">
                    No activity yet.
                  </p>
                ) : (
                  <ol className="relative space-y-4 border-l pl-5">
                    {timeline.map((ev) => (
                      <li key={ev.key} className="relative">
                        <span className="absolute -left-[1.6rem] top-1 size-2.5 rounded-full bg-brand-blue" />
                        <p className="text-sm font-medium">{ev.title}</p>
                        {ev.body && (
                          <p className="mt-0.5 text-sm text-muted-foreground whitespace-pre-wrap">
                            {ev.body}
                          </p>
                        )}
                        <p className="mt-0.5 text-xs text-muted-foreground">
                          {fmtDateTime(ev.at)}
                        </p>
                      </li>
                    ))}
                  </ol>
                )}
              </TabsContent>

              {/* Follow-ups */}
              <TabsContent value="followups" className="mt-4 space-y-4">
                <AddFollowupForm
                  leadId={lead.id}
                  followupTypes={options.followupTypes}
                />
                {followups.length === 0 ? (
                  <p className="text-sm text-muted-foreground">
                    No follow-ups scheduled.
                  </p>
                ) : (
                  <div className="space-y-3">
                    {followups.map((f) => (
                      <div key={f.id} className="rounded-lg border p-4">
                        <div className="flex items-start justify-between gap-3">
                          <div>
                            <p className="text-sm font-medium">
                              {oneName(f.type) || "Follow-up"}
                              {f.next_date
                                ? ` · ${fmtDate(f.next_date)}`
                                : ""}
                              {f.from_time
                                ? ` ${f.from_time}${
                                    f.to_time ? `–${f.to_time}` : ""
                                  }`
                                : ""}
                            </p>
                            {f.notes && (
                              <p className="mt-1 text-sm text-muted-foreground whitespace-pre-wrap">
                                {f.notes}
                              </p>
                            )}
                            {f.outcome && (
                              <p className="mt-1 text-sm">
                                <span className="text-muted-foreground">
                                  Outcome:{" "}
                                </span>
                                {f.outcome}
                              </p>
                            )}
                          </div>
                          <Badge
                            variant={
                              f.status === "done"
                                ? "secondary"
                                : f.status === "missed"
                                  ? "destructive"
                                  : "default"
                            }
                          >
                            {f.status}
                          </Badge>
                        </div>
                        {f.status === "pending" && (
                          <CompleteFollowupButton
                            followupId={f.id}
                            leadId={lead.id}
                          />
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </TabsContent>

              {/* Notes */}
              <TabsContent value="notes" className="mt-4 space-y-4">
                <AddNoteForm leadId={lead.id} />
                {notes.length === 0 ? (
                  <p className="text-sm text-muted-foreground">No notes yet.</p>
                ) : (
                  <div className="space-y-3">
                    {notes.map((n) => (
                      <div key={n.id} className="rounded-lg border p-4">
                        <p className="text-sm whitespace-pre-wrap">{n.body}</p>
                        <p className="mt-1.5 text-xs text-muted-foreground">
                          {fmtDateTime(n.created_at)}
                        </p>
                      </div>
                    ))}
                  </div>
                )}
              </TabsContent>

              {/* Assignment */}
              <TabsContent value="assignment" className="mt-4 space-y-4">
                <div>
                  <p className="mb-1.5 text-sm font-medium">
                    Currently assigned
                  </p>
                  {assignedNames.length === 0 ? (
                    <p className="text-sm text-muted-foreground">
                      No one assigned yet.
                    </p>
                  ) : (
                    <div className="flex flex-wrap gap-1.5">
                      {assignedNames.map((name, i) => (
                        <Badge key={i} variant="secondary">
                          {name}
                        </Badge>
                      ))}
                    </div>
                  )}
                </div>
                <Separator />
                <AssignmentEditor
                  leadId={lead.id}
                  assignableUsers={options.assignableUsers}
                  currentUserIds={assignedUserIds}
                />
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
