"use client";

import { CompanyProfileHero } from "@/components/market/company-profile-hero";
import {
  ProfileLink,
  ProfileSection,
  ProfileTable,
  formatDate,
  resolvePopulatedCampaign,
} from "@/components/market/profile-tables";
import { Badge } from "@/components/ui/badge";
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 CompanyDetailPayload = {
  company: Record<string, unknown>;
  people: Record<string, unknown>[];
  contactPoints: Record<string, unknown>[];
  serviceMatches: 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 CompanyDetailClient({
  id,
  detail,
}: {
  id: string;
  detail: CompanyDetailPayload;
}) {
  const { locale } = useLocale();
  const company = detail.company;

  const tabs = locale === "ar"
    ? [
        ["overview", "نظرة عامة"],
        ["people", "الأشخاص"],
        ["contacts", "الاتصال"],
        ["campaigns", "الحملات"],
        ["inbox", "الصندوق"],
        ["leads", "العملاء"],
        ["opportunities", "الفرص"],
        ["activities", "النشاط"],
      ]
    : [
        ["overview", "Overview"],
        ["people", "People"],
        ["contacts", "Contacts"],
        ["campaigns", "Campaigns"],
        ["inbox", "Inbox"],
        ["leads", "Leads"],
        ["opportunities", "Opportunities"],
        ["activities", "Activity"],
      ];

  return (
    <div className="animate-fade-in space-y-6">
      <CompanyProfileHero id={id} company={company} />

      <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" ? "المدينة" : "City"} value={company.city} />
              <Info label={locale === "ar" ? "المنطقة" : "Region"} value={company.region} />
              <Info label={locale === "ar" ? "النشاط" : "Activity"} value={company.activity} />
              <Info label={locale === "ar" ? "الثقة" : "Confidence"} value={company.dataConfidence} />
              <Info label="Website" value={company.website} link />
              <Info label="LinkedIn" value={company.linkedinUrl} link />
            </dl>
          </ProfileSection>
          <div className="mt-4 grid gap-4 md:grid-cols-2">
            <AiLeadScorePanel
              entityType="company"
              entityId={id}
              initialScore={company.aiLeadScore as number | undefined}
              initialGrade={company.aiLeadGrade as string | undefined}
              initialReason={company.aiScoreReason as string | undefined}
            />
            <AiNextBestActionPanel entityType="company" entityId={id} />
          </div>
          {detail.serviceMatches.length > 0 ? (
            <ProfileSection title={locale === "ar" ? "مطابقة الخدمات" : "Service matches"}>
              <ProfileTable
                headers={["Service", "Fit", "Priority"]}
                rows={detail.serviceMatches.map((s) => [
                  String(s.recommendedService ?? "—"),
                  String(s.fitScore ?? "—"),
                  String(s.priority ?? "—"),
                ])}
              />
            </ProfileSection>
          ) : null}
        </TabsContent>

        <TabsContent value="people">
          <ProfileSection title={`${locale === "ar" ? "الأشخاص" : "People"} (${detail.people.length})`}>
            <ProfileTable
              headers={["Name", "Title", "Email", ""]}
              rows={detail.people.map((p) => [
                <ProfileLink key={String(p._id)} href={`/market/people/${String(p._id)}`}>
                  {String(p.fullName)}
                </ProfileLink>,
                String(p.jobTitle ?? "—"),
                String(p.email ?? "—"),
                p.isDecisionMaker === "yes" ? (
                  <Badge variant="success">{locale === "ar" ? "صانع قرار" : "DM"}</Badge>
                ) : (
                  "—"
                ),
              ])}
            />
          </ProfileSection>
        </TabsContent>

        <TabsContent value="contacts">
          <ProfileSection title={locale === "ar" ? "نقاط الاتصال" : "Contact points"}>
            <ProfileTable
              headers={["Type", "Value", "Verified"]}
              rows={detail.contactPoints.map((c) => [
                String(c.contactType),
                String(c.contactValue),
                c.isVerified ? "✓" : "—",
              ])}
            />
          </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"]}
              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>,
              ])}
            />
          </ProfileSection>
        </TabsContent>

        <TabsContent value="leads">
          <ProfileSection title={locale === "ar" ? "العملاء المحتملون" : "Leads"}>
            <ProfileTable
              headers={["Status", "Temp", "Service"]}
              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 ?? "—"),
              ])}
            />
          </ProfileSection>
        </TabsContent>

        <TabsContent value="opportunities">
          <ProfileSection title={locale === "ar" ? "الفرص" : "Opportunities"}>
            <ProfileTable
              headers={["Stage", "Value", ""]}
              rows={detail.opportunities.map((o) => [
                String(o.stage ?? "—"),
                String(o.estimatedValue ?? "—"),
                <ProfileLink key={String(o._id)} href={`/opportunities/${String(o._id)}`}>
                  →
                </ProfileLink>,
              ])}
            />
          </ProfileSection>
        </TabsContent>

        <TabsContent value="activities">
          <div className="space-y-4">
            <ActivitySummaryCards companyId={id} />
            <ProfileSection title={locale === "ar" ? "النشاط" : "Activity"}>
              <ActivityTimeline
                companyId={id}
                noteEntityType="company"
                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>
  );
}
