"use client";

import { useState, useEffect } from "react";
import type { Partner } from "@/types/data";

interface ReorderTabProps {
  readonly partners: readonly Partner[];
  readonly onUpdate: () => void;
}

const DISPLAY_LIMIT = 10; // Maximum partners to display on site

export function ReorderTab({ partners, onUpdate }: ReorderTabProps) {
  const [displayPartners, setDisplayPartners] = useState<Partner[]>([]);
  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
  const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);

  useEffect(() => {
    // Initialize with partners that have display: true
    const displayed = partners.filter((p) => p.display !== false);
    setDisplayPartners(displayed);
  }, [partners]);

  const handleDragStart = (index: number) => {
    setDraggedIndex(index);
  };

  const handleDragOver = (e: React.DragEvent, index: number) => {
    e.preventDefault();
    e.stopPropagation();
    if (draggedIndex === null) return;

    setDragOverIndex(index);

    if (draggedIndex === index) return;

    const newPartners = [...displayPartners];
    const draggedItem = newPartners[draggedIndex];
    newPartners.splice(draggedIndex, 1);
    newPartners.splice(index, 0, draggedItem);
    setDisplayPartners(newPartners);
    setDraggedIndex(index);
  };

  const handleDragLeave = () => {
    setDragOverIndex(null);
  };

  const handleDragEnd = () => {
    setDraggedIndex(null);
    setDragOverIndex(null);
  };

  const handleAdd = (partner: Partner) => {
    if (displayPartners.length >= DISPLAY_LIMIT) {
      alert(`Maximum ${DISPLAY_LIMIT} partners can be displayed`);
      return;
    }
    if (displayPartners.some((p) => p.name === partner.name)) {
      alert("Partner is already in the display list");
      return;
    }
    setDisplayPartners([...displayPartners, partner]);
  };

  const handleRemove = (index: number) => {
    const newPartners = [...displayPartners];
    newPartners.splice(index, 1);
    setDisplayPartners(newPartners);
  };

  const handleSave = async () => {
    try {
      // Get all partners and update their display field
      const displayPartnerNames = displayPartners.map((p) => p.name);
      
      // Create updated partners list: display partners first (in order), then non-display partners
      const sortedPartners = [
        ...displayPartners.map((dp) => ({ ...dp, display: true })),
        ...partners.filter((p) => !displayPartnerNames.includes(p.name)).map((p) => ({ ...p, display: false }))
      ];

      await fetch("/api/admin/partners/reorder", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ partners: sortedPartners }),
      });
      alert("Order saved successfully!");
      onUpdate();
    } catch (error) {
      alert("Failed to save order");
    }
  };

  const availablePartners = partners.filter(
    (p) => !displayPartners.some((dp) => dp.name === p.name)
  );

  return (
    <div className="space-y-6">
      <div className="flex justify-between">
        <div>
          <h2 className="text-2xl font-bold text-slate-900">Reorder Partners</h2>
          <p className="mt-1 text-sm text-slate-600">
            Select and reorder partners to display on the site (max {DISPLAY_LIMIT}).
            Drag and drop to reorder. Click Save when done.
          </p>
        </div>
        <button
          onClick={handleSave}
          className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-blue-700"
        >
          Save Order
        </button>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        {/* Display List */}
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <h3 className="text-lg font-semibold text-slate-900">
              Display List ({displayPartners.length}/{DISPLAY_LIMIT})
            </h3>
            {displayPartners.length > 0 && (
              <button
                onClick={() => setDisplayPartners([])}
                className="text-sm text-red-600 hover:text-red-800"
              >
                Clear All
              </button>
            )}
          </div>
          <div className="space-y-2">
            {displayPartners.length === 0 ? (
              <div className="rounded-lg border-2 border-dashed border-slate-300 bg-slate-50 p-8 text-center">
                <p className="text-sm text-slate-500">
                  No partners in display list. Add partners from the available list.
                </p>
              </div>
            ) : (
              displayPartners.map((partner, index) => (
                <div
                  key={`${partner.name}-${index}`}
                  draggable
                  onDragStart={() => handleDragStart(index)}
                  onDragOver={(e) => handleDragOver(e, index)}
                  onDragLeave={handleDragLeave}
                  onDragEnd={handleDragEnd}
                  className={`flex cursor-grab active:cursor-grabbing items-center justify-between rounded-lg border-2 bg-white p-4 shadow-sm transition-all duration-200 ${
                    draggedIndex === index
                      ? "opacity-40 scale-95 border-blue-400 bg-blue-50"
                      : dragOverIndex === index
                      ? "border-blue-400 bg-blue-50 scale-105 shadow-lg"
                      : "border-slate-200 hover:border-blue-300 hover:shadow-md hover:scale-[1.02]"
                  }`}
                >
                  <div className="flex items-center space-x-4">
                    <div className="flex h-8 w-8 items-center justify-center rounded-full bg-blue-100 text-sm font-semibold text-blue-700">
                      {index + 1}
                    </div>
                    <div>
                      <div className="font-semibold text-slate-900">
                        {partner.name}
                      </div>
                      <div className="text-sm text-slate-500">
                        {partner.welcomeBonus}
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    {partner.licensed && (
                      <span className="rounded-full bg-green-100 px-2 py-1 text-xs font-medium text-green-800">
                        Licensed
                      </span>
                    )}
                    <button
                      onClick={() => handleRemove(index)}
                      className="rounded-lg bg-red-50 px-3 py-1 text-sm font-medium text-red-700 transition-colors hover:bg-red-100"
                    >
                      Remove
                    </button>
                    <svg
                      className="h-5 w-5 text-slate-400"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M4 8h16M4 16h16"
                      />
                    </svg>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>

        {/* Available Partners */}
        <div className="space-y-4">
          <h3 className="text-lg font-semibold text-slate-900">
            Available Partners ({availablePartners.length})
          </h3>
          <div className="max-h-[600px] space-y-2 overflow-y-auto">
            {availablePartners.length === 0 ? (
              <div className="rounded-lg border border-slate-200 bg-slate-50 p-4 text-center">
                <p className="text-sm text-slate-500">
                  All partners are in the display list.
                </p>
              </div>
            ) : (
              availablePartners.map((partner, index) => (
                <div
                  key={`available-${partner.name}-${index}`}
                  className="flex items-center justify-between rounded-lg border border-slate-200 bg-white p-4 shadow-sm"
                >
                  <div className="flex items-center space-x-4">
                    <div>
                      <div className="font-semibold text-slate-900">
                        {partner.name}
                      </div>
                      <div className="text-sm text-slate-500">
                        {partner.welcomeBonus}
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    {partner.licensed && (
                      <span className="rounded-full bg-green-100 px-2 py-1 text-xs font-medium text-green-800">
                        Licensed
                      </span>
                    )}
                    <button
                      onClick={() => handleAdd(partner)}
                      disabled={displayPartners.length >= DISPLAY_LIMIT}
                      className="rounded-lg bg-blue-50 px-3 py-1 text-sm font-medium text-blue-700 transition-colors hover:bg-blue-100 disabled:cursor-not-allowed disabled:opacity-50"
                    >
                      Add
                    </button>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
