"use client";

import { useState, useCallback } from "react";
import {
  Lock,
  ArrowRight,
  CheckCircle,
  Users,
  Kanban,
  BarChart3,
  Settings,
  FileInput,
  Zap,
} from "lucide-react";
import type { Lang } from "@/lib/config";
import type { LeadOutput } from "@/lib/types/lead-crm.types";
import { useLeadData } from "./useLeadData";
import LeadListView from "./LeadListView";
import PipelineView from "./PipelineView";
import LeadDetailDrawer from "./LeadDetailDrawer";
import CaptureFormsManager from "./CaptureFormsManager";
import NurtureSequencesList from "./NurtureSequencesList";
import ScoringDashboard from "./ScoringDashboard";
import ScoringRulesConfig from "./ScoringRulesConfig";
import CreateLeadModal from "./CreateLeadModal";

type SubTab =
  | "leads"
  | "pipeline"
  | "scoring"
  | "scoring-rules"
  | "capture-forms"
  | "nurture";

interface SubTabConfig {
  id: SubTab;
  labelEn: string;
  labelAr: string;
  icon: React.ReactNode;
}

const SUB_TABS: SubTabConfig[] = [
  {
    id: "leads",
    labelEn: "Leads",
    labelAr: "العملاء",
    icon: <Users className="h-4 w-4" />,
  },
  {
    id: "pipeline",
    labelEn: "Pipeline",
    labelAr: "خط الأنابيب",
    icon: <Kanban className="h-4 w-4" />,
  },
  {
    id: "scoring",
    labelEn: "Scoring",
    labelAr: "التسجيل",
    icon: <BarChart3 className="h-4 w-4" />,
  },
  {
    id: "scoring-rules",
    labelEn: "Rules",
    labelAr: "القواعد",
    icon: <Settings className="h-4 w-4" />,
  },
  {
    id: "capture-forms",
    labelEn: "Capture",
    labelAr: "الالتقاط",
    icon: <FileInput className="h-4 w-4" />,
  },
  {
    id: "nurture",
    labelEn: "Nurture",
    labelAr: "الرعاية",
    icon: <Zap className="h-4 w-4" />,
  },
];

interface LeadsCRMPanelProps {
  lang: Lang;
  hasAccess?: boolean;
}

export default function LeadsCRMPanel({ lang, hasAccess }: LeadsCRMPanelProps) {
  const isAr = lang === "ar";

  if (hasAccess === false) {
    return <UpgradePrompt isAr={isAr} />;
  }

  return <LeadsCRMDashboard isAr={isAr} />;
}

function LeadsCRMDashboard({ isAr }: { isAr: boolean }) {
  const [activeSubTab, setActiveSubTab] = useState<SubTab>("leads");
  const [selectedLead, setSelectedLead] = useState<LeadOutput | null>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);

  const {
    leads,
    leadsLoading,
    stats,
    pipeline,
    pipelineLoading,
    sequences,
    captureForms,
    scoringRules,
    refreshLeads,
    refreshPipeline,
    refreshStats,
    refreshSequences,
    refreshCaptureForms,
    refreshScoringRules,
  } = useLeadData();

  const handleSelectLead = useCallback((lead: LeadOutput) => {
    setSelectedLead(lead);
  }, []);

  const handleMoveLead = useCallback(
    async (leadId: string, stageId: string) => {
      try {
        await fetch(`/api/leads/${leadId}/move`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ pipelineStageId: stageId }),
        });
        refreshPipeline();
      } catch {
        // silent
      }
    },
    [refreshPipeline],
  );

  const handleRefreshAll = useCallback(() => {
    refreshLeads();
    refreshPipeline();
    refreshStats();
  }, [refreshLeads, refreshPipeline, refreshStats]);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-slate-900">
            {isAr ? "العملاء المحتملون وإدارة العلاقات" : "Leads & CRM"}
          </h2>
          <p className="text-slate-500 mt-1">
            {isAr
              ? "أدر عملاءك المحتملين وتتبع خط الأنابيب"
              : "Manage your leads and track the sales pipeline"}
          </p>
        </div>
        {stats && (
          <div className="flex items-center gap-4 text-sm">
            <div className="text-right">
              <p className="text-xs text-slate-500">
                {isAr ? "إجمالي العملاء" : "Total Leads"}
              </p>
              <p className="font-bold text-slate-900">{stats.total || 0}</p>
            </div>
            <div className="text-right">
              <p className="text-xs text-slate-500">
                {isAr ? "معدل التحويل" : "Conversion"}
              </p>
              <p className="font-bold text-emerald-600">
                {stats.conversionRate
                  ? `${Math.round(stats.conversionRate)}%`
                  : "0%"}
              </p>
            </div>
          </div>
        )}
      </div>

      {/* Sub-tab navigation */}
      <div className="flex gap-1 p-1 bg-slate-100 rounded-xl w-fit overflow-x-auto">
        {SUB_TABS.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveSubTab(tab.id)}
            className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all whitespace-nowrap ${
              activeSubTab === tab.id
                ? "bg-white text-slate-900 shadow-sm"
                : "text-slate-500 hover:text-slate-700"
            }`}
          >
            {tab.icon}
            {isAr ? tab.labelAr : tab.labelEn}
          </button>
        ))}
      </div>

      {/* Tab content */}
      {activeSubTab === "leads" && (
        <LeadListView
          isAr={isAr}
          leads={leads}
          loading={leadsLoading}
          onRefresh={refreshLeads}
          onSelectLead={handleSelectLead}
          onCreateLead={() => setShowCreateModal(true)}
        />
      )}
      {activeSubTab === "pipeline" && (
        <PipelineView
          isAr={isAr}
          pipeline={pipeline}
          loading={pipelineLoading}
          onSelectLead={handleSelectLead}
          onMoveLead={handleMoveLead}
        />
      )}
      {activeSubTab === "scoring" && (
        <ScoringDashboard
          isAr={isAr}
          leads={leads}
          scoringRules={scoringRules}
        />
      )}
      {activeSubTab === "scoring-rules" && (
        <ScoringRulesConfig
          isAr={isAr}
          rules={scoringRules}
          onRefresh={refreshScoringRules}
        />
      )}
      {activeSubTab === "capture-forms" && (
        <CaptureFormsManager
          isAr={isAr}
          forms={captureForms}
          onRefresh={refreshCaptureForms}
        />
      )}
      {activeSubTab === "nurture" && (
        <NurtureSequencesList
          isAr={isAr}
          sequences={sequences}
          onRefresh={refreshSequences}
        />
      )}

      {/* Lead detail drawer */}
      {selectedLead && (
        <LeadDetailDrawer
          isAr={isAr}
          lead={selectedLead}
          onClose={() => setSelectedLead(null)}
          onRefresh={handleRefreshAll}
        />
      )}

      {/* Create lead modal */}
      {showCreateModal && (
        <CreateLeadModal
          isAr={isAr}
          onClose={() => setShowCreateModal(false)}
          onCreated={handleRefreshAll}
        />
      )}
    </div>
  );
}

function UpgradePrompt({ isAr }: { isAr: boolean }) {
  return (
    <div className="space-y-8">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-slate-900">
            {isAr ? "العملاء المحتملون وإدارة العلاقات" : "Leads & CRM"}
          </h2>
          <p className="text-slate-500 mt-1">
            {isAr
              ? "إدارة شاملة للعملاء المحتملين بالذكاء الاصطناعي"
              : "AI-powered lead generation and CRM"}
          </p>
        </div>
      </div>

      <div className="bg-white rounded-2xl border border-slate-200 p-10 text-center shadow-sm">
        <div className="mx-auto w-16 h-16 rounded-2xl bg-gradient-to-br from-slate-100 to-slate-200 flex items-center justify-center mb-5">
          <Lock className="h-8 w-8 text-slate-400" />
        </div>
        <h3 className="text-xl font-bold text-slate-900 mb-2">
          {isAr
            ? "إدارة العملاء المحتملون متاحة في الخطة النهائية"
            : "Leads & CRM Available on Ultimate Plan"}
        </h3>
        <p className="text-slate-500 max-w-md mx-auto mb-6">
          {isAr
            ? "قم بالترقية إلى الخطة النهائية للحصول على توليد عملاء محتملين بالذكاء الاصطناعي، تسجيل النقاط التلقائي، وأتمتة الرعاية"
            : "Upgrade to the Ultimate plan for AI lead generation, automated scoring, pipeline management, and nurture sequences"}
        </p>
        <div className="flex flex-wrap justify-center gap-3 mb-8">
          {[
            { en: "AI Lead Generation", ar: "توليد عملاء بالذكاء الاصطناعي" },
            { en: "Lead Scoring", ar: "تسجيل نقاط العملاء" },
            { en: "Sales Pipeline", ar: "خط أنابيب المبيعات" },
            { en: "Nurture Automation", ar: "أتمتة الرعاية" },
            { en: "Capture Forms", ar: "نماذج الالتقاط" },
          ].map((feature) => (
            <span
              key={feature.en}
              className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-emerald-50 text-emerald-700 text-sm font-medium"
            >
              <CheckCircle className="h-3.5 w-3.5" />
              {isAr ? feature.ar : feature.en}
            </span>
          ))}
        </div>
        <button className="px-6 py-3 bg-brand-green text-white rounded-xl text-sm font-semibold hover:bg-brand-green/90 transition-colors inline-flex items-center gap-2">
          {isAr ? "ترقية الآن" : "Upgrade Now"}
          <ArrowRight className={`h-4 w-4 ${isAr ? "rotate-180" : ""}`} />
        </button>
      </div>
    </div>
  );
}
