"use client";

import { useState } from "react";
import { Phone, Envelope, CaretRight } from '@/lib/icons';
import { toast } from "sonner";

import { Badge } from "@/components/ui/badge";
import { updateCustomerStageAction } from "@/lib/appwrite/customer-actions";
import {
  CUSTOMER_STAGE_LABELS,
  CUSTOMER_TYPE_LABELS,
  type Customer,
  type CustomerStage,
} from "@/lib/appwrite/schema";

const STAGES: CustomerStage[] = [
  "ilk_temas",
  "aktif_arama",
  "teklif",
  "sozlesme",
  "kapandi",
];

const STAGE_COLORS: Record<CustomerStage, string> = {
  ilk_temas: "bg-slate-100 dark:bg-slate-800/60",
  aktif_arama: "bg-blue-50 dark:bg-blue-950/40",
  teklif: "bg-amber-50 dark:bg-amber-950/40",
  sozlesme: "bg-purple-50 dark:bg-purple-950/40",
  kapandi: "bg-emerald-50 dark:bg-emerald-950/40",
};

const STAGE_HEADER_COLORS: Record<CustomerStage, string> = {
  ilk_temas: "border-slate-300 text-slate-600 dark:border-slate-600 dark:text-slate-400",
  aktif_arama: "border-blue-300 text-blue-700 dark:border-blue-600 dark:text-blue-400",
  teklif: "border-amber-300 text-amber-700 dark:border-amber-600 dark:text-amber-400",
  sozlesme: "border-purple-300 text-purple-700 dark:border-purple-600 dark:text-purple-400",
  kapandi: "border-emerald-300 text-emerald-700 dark:border-emerald-600 dark:text-emerald-400",
};

interface CustomersPipelineProps {
  customers: Customer[];
  onEdit: (c: Customer) => void;
}

export function CustomersPipeline({ customers, onEdit }: CustomersPipelineProps) {
  const [items, setItems] = useState(customers);

  async function moveStage(customer: Customer, stage: CustomerStage) {
    setItems((prev) =>
      prev.map((c) => (c.$id === customer.$id ? { ...c, stage } : c)),
    );
    const result = await updateCustomerStageAction(customer.$id, stage);
    if (!result.ok) {
      setItems((prev) =>
        prev.map((c) => (c.$id === customer.$id ? customer : c)),
      );
      toast.error(result.error ?? "Aşama güncellenemedi.");
    }
  }

  const grouped = STAGES.reduce<Record<CustomerStage, Customer[]>>(
    (acc, s) => {
      acc[s] = items.filter((c) => (c.stage ?? "ilk_temas") === s);
      return acc;
    },
    {} as Record<CustomerStage, Customer[]>,
  );

  return (
    <div className="flex gap-3 overflow-x-auto pb-2 min-h-0 flex-1">
      {STAGES.map((stage) => (
        <div key={stage} className="flex flex-col gap-2 w-60 shrink-0">
          {/* Column header */}
          <div className={`flex items-center justify-between rounded-lg border px-3 py-2 ${STAGE_HEADER_COLORS[stage]}`}>
            <span className="text-sm font-semibold">{CUSTOMER_STAGE_LABELS[stage]}</span>
            <span className="text-xs font-mono bg-white/60 dark:bg-black/20 rounded px-1.5 py-0.5">
              {grouped[stage].length}
            </span>
          </div>

          {/* Cards */}
          <div className={`flex flex-col gap-2 rounded-xl p-2 min-h-[6rem] flex-1 ${STAGE_COLORS[stage]}`}>
            {grouped[stage].length === 0 && (
              <p className="text-xs text-muted-foreground text-center py-4">Müşteri yok</p>
            )}
            {grouped[stage].map((c) => (
              <CustomerCard
                key={c.$id}
                customer={c}
                currentStage={stage}
                onMove={moveStage}
                onEdit={onEdit}
              />
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function CustomerCard({
  customer,
  currentStage,
  onMove,
  onEdit,
}: {
  customer: Customer;
  currentStage: CustomerStage;
  onMove: (c: Customer, s: CustomerStage) => void;
  onEdit: (c: Customer) => void;
}) {
  const currentIdx = STAGES.indexOf(currentStage);
  const nextStage = STAGES[currentIdx + 1] as CustomerStage | undefined;

  return (
    <div
      className="bg-card rounded-lg border p-3 space-y-2 shadow-xs hover:shadow-sm transition-shadow cursor-pointer group"
      onClick={() => onEdit(customer)}
    >
      <div className="flex items-start justify-between gap-1">
        <p className="text-sm font-medium leading-snug line-clamp-2 flex-1">{customer.name}</p>
        <Badge variant="outline" className="text-[10px] px-1 py-0 shrink-0">
          {CUSTOMER_TYPE_LABELS[customer.type] ?? customer.type}
        </Badge>
      </div>

      {(customer.phone || customer.email) && (
        <div className="space-y-0.5">
          {customer.phone && (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <Phone className="size-3" />
              <span className="truncate">{customer.phone}</span>
            </div>
          )}
          {customer.email && (
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <Envelope className="size-3" />
              <span className="truncate">{customer.email}</span>
            </div>
          )}
        </div>
      )}

      {customer.nextFollowUpDate && (
        <p className="text-[11px] text-amber-600 dark:text-amber-400 font-medium">
          📅 {new Date(customer.nextFollowUpDate).toLocaleDateString("tr-TR")}
        </p>
      )}

      {nextStage && (
        <button
          type="button"
          onClick={(e) => { e.stopPropagation(); onMove(customer, nextStage); }}
          className="w-full flex items-center justify-center gap-1 text-[11px] text-muted-foreground hover:text-foreground border border-dashed rounded py-0.5 hover:border-foreground/30 transition-colors opacity-0 group-hover:opacity-100"
        >
          <CaretRight className="size-3" />
          {CUSTOMER_STAGE_LABELS[nextStage]}
        </button>
      )}
    </div>
  );
}
