"use client";

import { useState, useCallback, useEffect } from "react";
import {
  X,
  Mail,
  Phone,
  Building2,
  Calendar,
  Sparkles,
  Loader2,
  MessageSquare,
  Clock,
  Plus,
} from "lucide-react";
import type {
  LeadOutput,
  LeadActivityOutput,
} from "@/lib/types/lead-crm.types";
import LeadScoreBadge from "./LeadScoreBadge";
import { GradeLabel } from "./LeadScoreBadge";
import { getLeadGrade } from "@/lib/types/lead-crm.types";

interface LeadDetailDrawerProps {
  isAr: boolean;
  lead: LeadOutput;
  onClose: () => void;
  onRefresh: () => void;
}

export default function LeadDetailDrawer({
  isAr,
  lead,
  onClose,
  onRefresh,
}: LeadDetailDrawerProps) {
  const [activities, setActivities] = useState<LeadActivityOutput[]>([]);
  const [activitiesLoading, setActivitiesLoading] = useState(true);
  const [qualifying, setQualifying] = useState(false);
  const [newNote, setNewNote] = useState("");
  const [addingNote, setAddingNote] = useState(false);

  useEffect(() => {
    async function loadActivities() {
      setActivitiesLoading(true);
      try {
        const res = await fetch(`/api/leads/${lead.id}/activities`);
        if (res.ok) {
          const json = await res.json();
          setActivities(json.data || []);
        }
      } catch {
        // silent
      } finally {
        setActivitiesLoading(false);
      }
    }
    loadActivities();
  }, [lead.id]);

  const handleQualify = useCallback(async () => {
    setQualifying(true);
    try {
      await fetch(`/api/leads/${lead.id}/qualify`, { method: "POST" });
      onRefresh();
    } catch {
      // silent
    } finally {
      setQualifying(false);
    }
  }, [lead.id, onRefresh]);

  const handleAddNote = useCallback(async () => {
    if (!newNote.trim()) return;
    setAddingNote(true);
    try {
      const res = await fetch(`/api/leads/${lead.id}/activities`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          type: "NOTE",
          title: isAr ? "ملاحظة" : "Note",
          description: newNote,
        }),
      });
      if (res.ok) {
        const json = await res.json();
        setActivities((prev) => [json.data, ...prev]);
        setNewNote("");
      }
    } catch {
      // silent
    } finally {
      setAddingNote(false);
    }
  }, [lead.id, newNote, isAr]);

  const activityIcons: Record<string, React.ReactNode> = {
    NOTE: <MessageSquare className="h-3.5 w-3.5" />,
    CALL: <Phone className="h-3.5 w-3.5" />,
    EMAIL: <Mail className="h-3.5 w-3.5" />,
    MEETING: <Calendar className="h-3.5 w-3.5" />,
    WHATSAPP: <MessageSquare className="h-3.5 w-3.5" />,
    AI_QUALIFICATION: <Sparkles className="h-3.5 w-3.5" />,
    SCORE_CHANGE: <Sparkles className="h-3.5 w-3.5" />,
    STATUS_CHANGE: <Clock className="h-3.5 w-3.5" />,
    STAGE_CHANGE: <Clock className="h-3.5 w-3.5" />,
  };

  return (
    <div className="fixed inset-y-0 right-0 w-full sm:w-[420px] bg-white shadow-2xl z-50 flex flex-col">
      {/* Header */}
      <div className="flex items-center justify-between px-5 py-4 border-b border-slate-200">
        <h3 className="text-lg font-bold text-slate-900">
          {isAr ? "تفاصيل العميل" : "Lead Details"}
        </h3>
        <button
          onClick={onClose}
          className="p-1.5 rounded-lg hover:bg-slate-100 transition-colors"
        >
          <X className="h-5 w-5 text-slate-500" />
        </button>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-5 space-y-6">
        {/* Lead info */}
        <div className="flex items-start gap-4">
          <div className="w-14 h-14 rounded-2xl bg-indigo-100 flex items-center justify-center flex-shrink-0">
            <span className="text-xl font-bold text-indigo-700">
              {lead.name[0]?.toUpperCase()}
            </span>
          </div>
          <div className="flex-1 min-w-0">
            <h4 className="text-lg font-bold text-slate-900">{lead.name}</h4>
            {lead.company && (
              <p className="text-sm text-slate-500 flex items-center gap-1">
                <Building2 className="h-3.5 w-3.5" />
                {lead.company}
              </p>
            )}
            <div className="flex items-center gap-2 mt-2">
              <LeadScoreBadge score={lead.score} />
              <GradeLabel grade={getLeadGrade(lead.score)} isAr={isAr} />
            </div>
          </div>
        </div>

        {/* Contact info */}
        <div className="bg-slate-50 rounded-xl p-4 space-y-2">
          {lead.email && (
            <div className="flex items-center gap-2 text-sm">
              <Mail className="h-4 w-4 text-slate-400" />
              <a
                href={`mailto:${lead.email}`}
                className="text-indigo-600 hover:underline"
              >
                {lead.email}
              </a>
            </div>
          )}
          {lead.phone && (
            <div className="flex items-center gap-2 text-sm">
              <Phone className="h-4 w-4 text-slate-400" />
              <a
                href={`tel:${lead.phone}`}
                className="text-indigo-600 hover:underline"
              >
                {lead.phone}
              </a>
            </div>
          )}
          {lead.dealValue && (
            <div className="flex items-center gap-2 text-sm">
              <span className="text-slate-400 font-medium">
                {isAr ? "قيمة الصفقة:" : "Deal value:"}
              </span>
              <span className="font-semibold text-emerald-600">
                {lead.dealCurrency || "QAR"} {lead.dealValue.toLocaleString()}
              </span>
            </div>
          )}
          {lead.source && (
            <div className="flex items-center gap-2 text-sm">
              <span className="text-slate-400 font-medium">
                {isAr ? "المصدر:" : "Source:"}
              </span>
              <span className="text-slate-700">{lead.source}</span>
            </div>
          )}
        </div>

        {/* Tags */}
        {lead.tags && lead.tags.length > 0 && (
          <div className="flex flex-wrap gap-1.5">
            {lead.tags.map((tag) => (
              <span
                key={tag}
                className="px-2 py-0.5 bg-indigo-50 text-indigo-700 text-xs rounded-full"
              >
                {tag}
              </span>
            ))}
          </div>
        )}

        {/* AI Qualify button */}
        <button
          onClick={handleQualify}
          disabled={qualifying}
          className="w-full py-2.5 bg-gradient-to-r from-violet-600 to-purple-600 text-white rounded-xl text-sm font-semibold hover:from-violet-700 hover:to-purple-700 disabled:opacity-50 flex items-center justify-center gap-2 transition-all"
        >
          {qualifying ? (
            <Loader2 className="h-4 w-4 animate-spin" />
          ) : (
            <Sparkles className="h-4 w-4" />
          )}
          {isAr ? "تأهيل بالذكاء الاصطناعي" : "AI Qualify"}
        </button>

        {/* Add note */}
        <div>
          <div className="flex items-center gap-2 mb-2">
            <Plus className="h-4 w-4 text-slate-400" />
            <span className="text-sm font-medium text-slate-700">
              {isAr ? "إضافة ملاحظة" : "Add Note"}
            </span>
          </div>
          <div className="flex gap-2">
            <input
              value={newNote}
              onChange={(e) => setNewNote(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && handleAddNote()}
              placeholder={isAr ? "اكتب ملاحظة..." : "Type a note..."}
              className="flex-1 px-3 py-2 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-200"
              dir={isAr ? "rtl" : "ltr"}
            />
            <button
              onClick={handleAddNote}
              disabled={!newNote.trim() || addingNote}
              className="px-3 py-2 bg-indigo-600 text-white rounded-xl text-sm hover:bg-indigo-700 disabled:opacity-50 transition-colors"
            >
              {addingNote ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : isAr ? (
                "إضافة"
              ) : (
                "Add"
              )}
            </button>
          </div>
        </div>

        {/* Activity Timeline */}
        <div>
          <h5 className="text-sm font-semibold text-slate-900 mb-3">
            {isAr ? "سجل الأنشطة" : "Activity Timeline"}
          </h5>
          {activitiesLoading ? (
            <div className="flex justify-center py-8">
              <Loader2 className="h-5 w-5 animate-spin text-slate-400" />
            </div>
          ) : activities.length === 0 ? (
            <p className="text-sm text-slate-400 text-center py-4">
              {isAr ? "لا توجد أنشطة" : "No activities yet"}
            </p>
          ) : (
            <div className="relative">
              <div className="absolute left-[15px] top-0 bottom-0 w-px bg-slate-200" />
              <div className="space-y-4">
                {activities.map((activity) => (
                  <div key={activity.id} className="flex gap-3 relative">
                    <div className="w-[30px] h-[30px] rounded-full bg-white border-2 border-slate-200 flex items-center justify-center flex-shrink-0 z-10 text-slate-500">
                      {activityIcons[activity.type] || (
                        <Clock className="h-3.5 w-3.5" />
                      )}
                    </div>
                    <div className="flex-1 min-w-0 pb-2">
                      <p className="text-sm font-medium text-slate-900">
                        {activity.title}
                      </p>
                      {activity.description && (
                        <p className="text-xs text-slate-500 mt-0.5">
                          {activity.description}
                        </p>
                      )}
                      <p className="text-[10px] text-slate-400 mt-1">
                        {new Date(activity.createdAt).toLocaleDateString(
                          isAr ? "ar-SA" : "en-US",
                          {
                            month: "short",
                            day: "numeric",
                            hour: "2-digit",
                            minute: "2-digit",
                          },
                        )}
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
