"use client";

import { useCallback } from "react";
import { Loader2, GripVertical, DollarSign } from "lucide-react";
import type {
  PipelineView as PipelineViewType,
  LeadOutput,
} from "@/lib/types/lead-crm.types";
import LeadScoreBadge from "./LeadScoreBadge";

interface PipelineViewProps {
  isAr: boolean;
  pipeline: PipelineViewType | null;
  loading: boolean;
  onSelectLead: (lead: LeadOutput) => void;
  onMoveLead: (leadId: string, stageId: string) => void;
}

export default function PipelineView({
  isAr,
  pipeline,
  loading,
  onSelectLead,
  onMoveLead,
}: PipelineViewProps) {
  const handleDragStart = useCallback((e: React.DragEvent, leadId: string) => {
    e.dataTransfer.setData("leadId", leadId);
  }, []);

  const handleDrop = useCallback(
    (e: React.DragEvent, stageId: string) => {
      e.preventDefault();
      const leadId = e.dataTransfer.getData("leadId");
      if (leadId) onMoveLead(leadId, stageId);
    },
    [onMoveLead],
  );

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 animate-spin text-indigo-500" />
      </div>
    );
  }

  if (!pipeline || pipeline.stages.length === 0) {
    return (
      <div className="text-center py-16 text-slate-400">
        <p className="text-sm">
          {isAr
            ? "لم يتم إعداد مراحل الأنبوب بعد"
            : "No pipeline stages set up yet"}
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Summary bar */}
      <div className="flex items-center gap-4 text-sm">
        <span className="text-slate-500">
          {isAr ? "إجمالي العملاء:" : "Total leads:"}{" "}
          <span className="font-semibold text-slate-900">
            {pipeline.totalLeads}
          </span>
        </span>
        <span className="text-slate-500">
          {isAr ? "قيمة الصفقات:" : "Deal value:"}{" "}
          <span className="font-semibold text-slate-900">
            QAR {pipeline.totalDealValue.toLocaleString()}
          </span>
        </span>
      </div>

      {/* Kanban board */}
      <div className="flex gap-4 overflow-x-auto pb-4">
        {pipeline.stages.map((stage) => (
          <div
            key={stage.id}
            className="min-w-[280px] max-w-[320px] flex-shrink-0"
            onDrop={(e) => handleDrop(e, stage.id)}
            onDragOver={handleDragOver}
          >
            {/* Stage header */}
            <div className="flex items-center gap-2 mb-3 px-1">
              <div
                className="w-3 h-3 rounded-full"
                style={{ backgroundColor: stage.color }}
              />
              <h4 className="text-sm font-semibold text-slate-900">
                {isAr && stage.nameAr ? stage.nameAr : stage.name}
              </h4>
              <span className="text-xs text-slate-400 bg-slate-100 px-1.5 py-0.5 rounded-full">
                {stage.leads.length}
              </span>
            </div>

            {/* Lead cards */}
            <div className="space-y-2 min-h-[100px] p-2 bg-slate-50/50 rounded-xl border border-dashed border-slate-200">
              {stage.leads.map((lead) => (
                <div
                  key={lead.id}
                  draggable
                  onDragStart={(e) => handleDragStart(e, lead.id)}
                  onClick={() => onSelectLead(lead)}
                  className="bg-white rounded-xl border border-slate-200 p-3 cursor-pointer hover:shadow-md transition-shadow group"
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-slate-900 truncate">
                        {lead.name}
                      </p>
                      {lead.company && (
                        <p className="text-xs text-slate-500 truncate">
                          {lead.company}
                        </p>
                      )}
                    </div>
                    <GripVertical className="h-4 w-4 text-slate-300 opacity-0 group-hover:opacity-100 transition-opacity cursor-grab" />
                  </div>

                  <div className="flex items-center justify-between mt-2">
                    <LeadScoreBadge score={lead.score} size="sm" />
                    {lead.dealValue && (
                      <span className="flex items-center gap-0.5 text-xs text-emerald-600 font-medium">
                        <DollarSign className="h-3 w-3" />
                        {lead.dealValue.toLocaleString()}
                      </span>
                    )}
                  </div>

                  {lead.tags && lead.tags.length > 0 && (
                    <div className="flex flex-wrap gap-1 mt-2">
                      {lead.tags.slice(0, 2).map((tag) => (
                        <span
                          key={tag}
                          className="text-[10px] px-1.5 py-0.5 bg-indigo-50 text-indigo-600 rounded"
                        >
                          {tag}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
