"use client";

import { PersonProfileHero } from "@/components/market/person-profile-hero";
import {
  ProfileLink,
  ProfileSection,
  ProfileTable,
  formatDate,
  resolvePopulatedCampaign,
} from "@/components/market/profile-tables";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useLocale } from "@/components/providers/locale-provider";
import { ActivityTimeline } from "@/components/timeline/activity-timeline";
import { ActivitySummaryCards } from "@/components/timeline/activity-summary-cards";
import { AiLeadScorePanel } from "@/components/ai/ai-lead-score-panel";
import { AiNextBestActionPanel } from "@/components/ai/ai-next-best-action-panel";

export type PersonDetailPayload = {
  person: Record<string, unknown>;
  contactPoints: Record<string, unknown>[];
  campaignRecipients: Record<string, unknown>[];
  emailReplies: Record<string, unknown>[];
  leads: Record<string, unknown>[];
  opportunities: Record<string, unknown>[];
  activities: Record<string, unknown>[];
};

export function PersonDetailClient({
  id,
  detail,
}: {
  id: string;
  detail: PersonDetailPayload;
}) {
  const { locale } = useLocale();
  const person = detail.person;

  const tabs = locale === "ar"
    ? [
        ["overview", "نظرة عامة"],
        ["contacts", "الاتصال"],
        ["campaigns", "الحملات"],
        ["inbox", "الصندوق"],
        ["leads", "العملاء"],
        ["opportunities", "الفرص"],
        ["activities", "النشاط"],
      ]
    : [
        ["overview", "Overview"],
        ["contacts", "Contacts"],
        ["campaigns", "Campaigns"],
        ["inbox", "Inbox"],
        ["leads", "Leads"],
        ["opportunities", "Opportunities"],
        ["activities", "Activity"],
      ];

  return (
    <div className="animate-fade-in space-y-6">
      <PersonProfileHero id={id} person={person} />

      <Tabs defaultValue="overview">
        <TabsList className="flex h-auto w-full flex-wrap gap-1 rounded-xl bg-muted/50 p-1">
          {tabs.map(([value, label]) => (
            <TabsTrigger key={value} value={value}>
              {label}
            </TabsTrigger>
          ))}
        </TabsList>

        <TabsContent value="overview">
          <ProfileSection title={locale === "ar" ? "معلومات أساسية" : "Basic info"}>
            <dl className="grid gap-3 text-sm md:grid-cols-2 lg:grid-cols-3">
              <Info label={locale === "ar" ? "المسمى" : "Title"} value={person.jobTitle} />
              <Info label={locale === "ar" ? "القسم" : "Department"} value={person.department} />
              <Info label={locale === "ar" ? "المستوى" : "Seniority"} value={person.seniorityLevel} />
              <Info label={locale === "ar" ? "البريد" : "Email"} value={person.email} />
              <Info label={locale === "ar" ? "الجوال" : "Mobile"} value={person.mobile} />
              <Info label={locale === "ar" ? "الهاتف" : "Phone"} value={person.phone} />
              <Info label="LinkedIn" value={person.linkedinUrl} link />
            </dl>
            {person.notes ? (
              <p className="mt-4 text-sm text-muted-foreground">{String(person.notes)}</p>
            ) : null}
          </ProfileSection>
          <div className="mt-4 grid gap-4 md:grid-cols-2">
            <AiLeadScorePanel
              entityType="person"
              entityId={id}
              initialScore={person.aiLeadScore as number | undefined}
              initialGrade={person.aiLeadGrade as string | undefined}
              initialReason={person.aiScoreReason as string | undefined}
            />
            <AiNextBestActionPanel entityType="person" entityId={id} />
          </div>
        </TabsContent>

        <TabsContent value="contacts">
          <ProfileSection title={locale === "ar" ? "نقاط الاتصال" : "Contact points"}>
            <ProfileTable
              headers={["Type", "Value", "Verified", "Confidence"]}
              rows={detail.contactPoints.map((c) => [
                String(c.contactType),
                String(c.contactValue),
                c.isVerified ? "✓" : "—",
                String(c.dataConfidence ?? "—"),
              ])}
            />
          </ProfileSection>
        </TabsContent>

        <TabsContent value="campaigns">
          <ProfileSection title={locale === "ar" ? "سجل الحملات" : "Campaign history"}>
            <ProfileTable
              headers={["Campaign", "Email", "Status", "Sent"]}
              rows={detail.campaignRecipients.map((r) => {
                const campaign = resolvePopulatedCampaign(r.campaignId);
                return [
                  campaign?.name ? (
                    <ProfileLink href={`/campaigns/${campaign.id}`}>{campaign.name}</ProfileLink>
                  ) : (
                    "—"
                  ),
                  String(r.email ?? "—"),
                  String(r.status ?? "—"),
                  formatDate(r.sentAt as string | Date | undefined),
                ];
              })}
            />
          </ProfileSection>
        </TabsContent>

        <TabsContent value="inbox">
          <ProfileSection title={locale === "ar" ? "ردود الصندوق" : "Inbox replies"}>
            <ProfileTable
              headers={["From", "Subject", "Status", "Date"]}
              rows={detail.emailReplies.map((r) => [
                String(r.fromEmail ?? "—"),
                String(r.subject ?? "—"),
                <ProfileLink key={String(r._id)} href={`/inbox/${String(r._id)}`}>
                  {String(r.status)}
                </ProfileLink>,
                formatDate(r.receivedAt as string | Date | undefined),
              ])}
            />
          </ProfileSection>
        </TabsContent>

        <TabsContent value="leads">
          <ProfileSection title={locale === "ar" ? "العملاء المحتملون" : "Leads"}>
            <ProfileTable
              headers={["Status", "Temp", "Service", "Date"]}
              rows={detail.leads.map((l) => [
                <ProfileLink key={String(l._id)} href={`/leads/${String(l._id)}`}>
                  {String(l.status)}
                </ProfileLink>,
                String(l.temperature ?? "—"),
                String(l.serviceInterest ?? "—"),
                formatDate(l.createdAt as string | Date | undefined),
              ])}
            />
          </ProfileSection>
        </TabsContent>

        <TabsContent value="opportunities">
          <ProfileSection title={locale === "ar" ? "الفرص" : "Opportunities"}>
            <ProfileTable
              headers={["Stage", "Value", ""]}
              rows={detail.opportunities.map((o) => [
                <ProfileLink key={String(o._id)} href={`/opportunities/${String(o._id)}`}>
                  {String(o.stage)}
                </ProfileLink>,
                o.valueEstimate != null ? String(o.valueEstimate) : "—",
                formatDate(o.createdAt as string | Date | undefined),
              ])}
            />
          </ProfileSection>
        </TabsContent>

        <TabsContent value="activities">
          <div className="space-y-4">
            <ActivitySummaryCards personId={id} />
            <ProfileSection title={locale === "ar" ? "النشاط" : "Activity"}>
              <ActivityTimeline
                personId={id}
                noteEntityType="person"
                noteEntityId={id}
                showNoteForm
              />
            </ProfileSection>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}

function Info({
  label,
  value,
  link,
}: {
  label: string;
  value: unknown;
  link?: boolean;
}) {
  const v = value != null && value !== "" ? String(value) : "—";
  return (
    <div>
      <dt className="text-muted-foreground">{label}</dt>
      <dd className="font-medium">
        {link && v !== "—" ? (
          <a
            href={v.startsWith("http") ? v : `https://${v}`}
            target="_blank"
            rel="noreferrer"
            className="text-primary hover:underline"
          >
            {v}
          </a>
        ) : (
          v
        )}
      </dd>
    </div>
  );
}
