"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { TrendingUp } from "lucide-react";
import { ProfileHero } from "@/components/design-system/profile-hero";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useLocale } from "@/components/providers/locale-provider";

const STAGES = [
  "new_lead",
  "contacted",
  "interested",
  "meeting",
  "proposal",
  "negotiation",
  "won",
  "lost",
  "postponed",
];

export function OpportunityDetailClient({
  opportunity,
}: {
  opportunity: {
    _id: string;
    title: string;
    stage: string;
    probability?: number;
    service?: string;
    valueEstimate?: number;
    expectedCloseDate?: string;
    notes?: string;
    companyId?: { nameAr?: string };
    personId?: { fullName?: string };
    activities?: Array<{ title?: string; description?: string }>;
  };
}) {
  const router = useRouter();
  const { locale } = useLocale();
  const [stage, setStage] = useState(opportunity.stage);
  const [probability, setProbability] = useState(opportunity.probability ?? 0);
  const [message, setMessage] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function moveStage(next: string) {
    setLoading(true);
    const res = await fetch(`/api/opportunities/${opportunity._id}/move-stage`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ stage: next }),
    });
    const json = await res.json();
    setLoading(false);
    if (!res.ok) {
      setMessage(json.error ?? (locale === "ar" ? "فشل نقل المرحلة" : "Stage update failed"));
      return;
    }
    setStage(json.data.stage);
    setProbability(json.data.probability);
    setMessage(locale === "ar" ? "تم تحديث المرحلة" : "Stage updated");
    router.refresh();
  }

  async function closeWon() {
    setLoading(true);
    await fetch(`/api/opportunities/${opportunity._id}/close-won`, { method: "POST" });
    setLoading(false);
    router.refresh();
  }

  async function closeLost() {
    setLoading(true);
    await fetch(`/api/opportunities/${opportunity._id}/close-lost`, { method: "POST" });
    setLoading(false);
    router.refresh();
  }

  return (
    <div className="space-y-6">
      <ProfileHero
        icon={TrendingUp}
        title={opportunity.title}
        subtitle={opportunity.companyId?.nameAr}
        badges={
          <>
            <Badge variant="default">{stage}</Badge>
            <Badge variant="secondary">{probability}%</Badge>
            {opportunity.service ? (
              <Badge variant="secondary">{opportunity.service}</Badge>
            ) : null}
          </>
        }
        backHref="/pipeline"
        backLabel={locale === "ar" ? "← العودة لخط المبيعات" : "← Back to pipeline"}
      />

      <Tabs defaultValue="overview">
        <TabsList className="flex h-auto flex-wrap gap-1">
          <TabsTrigger value="overview">
            {locale === "ar" ? "نظرة عامة" : "Overview"}
          </TabsTrigger>
          <TabsTrigger value="actions">
            {locale === "ar" ? "إجراءات" : "Actions"}
          </TabsTrigger>
          <TabsTrigger value="activity">
            {locale === "ar" ? "الأنشطة" : "Activity"}
          </TabsTrigger>
        </TabsList>

        <TabsContent value="overview">
          <Card>
            <CardContent className="pt-6">
              <dl className="grid gap-3 text-sm md:grid-cols-2">
                <Info label={locale === "ar" ? "الشخص" : "Person"} value={opportunity.personId?.fullName} />
                <Info label={locale === "ar" ? "القيمة" : "Value"} value={opportunity.valueEstimate != null ? String(opportunity.valueEstimate) : undefined} />
                <Info label={locale === "ar" ? "ملاحظات" : "Notes"} value={opportunity.notes} />
              </dl>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="actions">
          <Card>
            <CardContent className="flex flex-wrap gap-2 pt-6">
              <select
                className="flex h-10 min-h-[44px] rounded-lg border border-border bg-card px-3 text-sm sm:min-h-10"
                value={stage}
                disabled={loading}
                onChange={(e) => void moveStage(e.target.value)}
              >
                {STAGES.map((s) => (
                  <option key={s} value={s}>
                    {s}
                  </option>
                ))}
              </select>
              <Button type="button" size="sm" disabled={loading} onClick={() => void closeWon()}>
                Won
              </Button>
              <Button type="button" variant="destructive" size="sm" disabled={loading} onClick={() => void closeLost()}>
                Lost
              </Button>
              {message ? <p className="w-full text-sm text-muted-foreground">{message}</p> : null}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="activity">
          <Card>
            <CardContent className="space-y-2 pt-6 text-sm">
              {(opportunity.activities ?? []).map((a, i) => (
                <div key={i} className="rounded-lg border border-border p-3">
                  <p className="font-medium">{a.title}</p>
                  <p className="text-muted-foreground">{a.description ?? ""}</p>
                </div>
              ))}
              {(opportunity.activities ?? []).length === 0 ? (
                <p className="text-muted-foreground">{locale === "ar" ? "لا أنشطة" : "No activity"}</p>
              ) : null}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}

function Info({ label, value }: { label: string; value?: string | null }) {
  return (
    <div>
      <dt className="text-muted-foreground">{label}</dt>
      <dd className="font-medium">{value ?? "—"}</dd>
    </div>
  );
}
