"use client";

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

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

export function PartnersTab({ partners, onUpdate }: PartnersTabProps) {
  const [editingIndex, setEditingIndex] = useState<number | null>(null);
  const [showAddForm, setShowAddForm] = useState(false);
  const [uploadingLogo, setUploadingLogo] = useState(false);
  const [formData, setFormData] = useState<Partner>({
    name: "",
    logo: "",
    welcomeBonus: "",
    affiliateLink: "",
    licensed: false,
    rating: 0,
  });

  const handleEdit = (index: number) => {
    setEditingIndex(index);
    setFormData(partners[index]);
    setShowAddForm(false);
  };

  const handleAdd = () => {
    setShowAddForm(true);
    setEditingIndex(null);
    setFormData({
      name: "",
      logo: "",
      welcomeBonus: "",
      affiliateLink: "",
      licensed: false,
      rating: 0,
    });
  };

  const handleSave = async () => {
    try {
      if (editingIndex !== null) {
        const oldPartner = partners[editingIndex];
        await fetch("/api/admin/partners", {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ 
            index: editingIndex, 
            partner: formData,
            oldLogo: oldPartner.logo 
          }),
        });
      } else {
        await fetch("/api/admin/partners", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(formData),
        });
      }
      setEditingIndex(null);
      setShowAddForm(false);
      onUpdate();
    } catch (error) {
      alert("Failed to save partner");
    }
  };

  const handleDelete = async (index: number) => {
    if (!confirm("Are you sure you want to delete this partner?")) return;

    try {
      await fetch("/api/admin/partners", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ index }),
      });
      onUpdate();
    } catch (error) {
      alert("Failed to delete partner");
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between">
        <h2 className="text-2xl font-bold text-slate-900">Manage Partners</h2>
        <button
          onClick={handleAdd}
          className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-blue-700"
        >
          Add Partner
        </button>
      </div>

      {(showAddForm || editingIndex !== null) && (
        <div className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
          <h3 className="mb-4 text-lg font-semibold">
            {editingIndex !== null ? "Edit Partner" : "Add New Partner"}
          </h3>
          <div className="grid gap-4 sm:grid-cols-2">
            <div>
              <label className="block text-sm font-medium text-slate-700">
                Name
              </label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) =>
                  setFormData({ ...formData, name: e.target.value })
                }
                className="mt-1 block w-full rounded-lg border border-slate-300 px-3 py-2 text-slate-900 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700">
                Logo
              </label>
              <div className="mt-1 space-y-2">
                <div className="relative">
                <input
                  type="file"
                  accept="image/*"
                    disabled={uploadingLogo}
                onChange={async (e) => {
                  const file = e.target.files?.[0];
                  if (file) {
                        setUploadingLogo(true);
                    const uploadFormData = new FormData();
                    uploadFormData.append('file', file);
                    uploadFormData.append('type', 'partner');
                    // Pass old logo path if editing
                    if (editingIndex !== null && formData.logo) {
                      uploadFormData.append('oldPath', formData.logo);
                    }
                    
                    try {
                      const res = await fetch('/api/admin/upload', {
                        method: 'POST',
                        body: uploadFormData,
                      });
                      const data = await res.json();
                      if (data.success) {
                        setFormData({ ...formData, logo: data.path });
                      } else {
                        alert('Failed to upload logo');
                      }
                    } catch (error) {
                      alert('Failed to upload logo');
                        } finally {
                          setUploadingLogo(false);
                    }
                  }
                }}
                    className="block w-full text-sm text-slate-600 file:mr-4 file:rounded-lg file:border-0 file:bg-blue-50 file:px-4 file:py-2 file:text-sm file:font-semibold file:text-blue-700 hover:file:bg-blue-100 disabled:opacity-50 disabled:cursor-not-allowed"
                />
                  {uploadingLogo && (
                    <div className="absolute inset-0 flex items-center justify-center bg-white/80 rounded-lg">
                      <div className="flex items-center gap-2 text-blue-600">
                        <svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        <span className="text-sm font-medium">Uploading...</span>
                      </div>
                    </div>
                  )}
                </div>
                <input
                  type="text"
                  value={formData.logo}
                  onChange={(e) =>
                    setFormData({ ...formData, logo: e.target.value })
                  }
                  className="block w-full rounded-lg border border-slate-300 px-3 py-2 text-slate-900 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
                  placeholder="/logos/example.webp"
                />
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700">
                Welcome Bonus
              </label>
              <input
                type="text"
                value={formData.welcomeBonus}
                onChange={(e) =>
                  setFormData({ ...formData, welcomeBonus: e.target.value })
                }
                className="mt-1 block w-full rounded-lg border border-slate-300 px-3 py-2 text-slate-900 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700">
                Rating
              </label>
              <input
                type="number"
                step="0.1"
                min="0"
                max="5"
                value={formData.rating}
                onChange={(e) =>
                  setFormData({
                    ...formData,
                    rating: parseFloat(e.target.value),
                  })
                }
                className="mt-1 block w-full rounded-lg border border-slate-300 px-3 py-2 text-slate-900 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
              />
            </div>
            <div className="sm:col-span-2">
              <label className="block text-sm font-medium text-slate-700">
                Affiliate Link
              </label>
              <input
                type="text"
                value={formData.affiliateLink}
                onChange={(e) =>
                  setFormData({ ...formData, affiliateLink: e.target.value })
                }
                className="mt-1 block w-full rounded-lg border border-slate-300 px-3 py-2 text-slate-900 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
              />
            </div>
            <div>
              <label className="flex items-center space-x-2">
                <input
                  type="checkbox"
                  checked={formData.licensed}
                  onChange={(e) =>
                    setFormData({ ...formData, licensed: e.target.checked })
                  }
                  className="h-4 w-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
                />
                <span className="text-sm font-medium text-slate-700">
                  Licensed
                </span>
              </label>
            </div>
          </div>
          <div className="mt-4 flex space-x-3">
            <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
            </button>
            <button
              onClick={() => {
                setShowAddForm(false);
                setEditingIndex(null);
              }}
              className="rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 transition-colors hover:bg-slate-50"
            >
              Cancel
            </button>
          </div>
        </div>
      )}

      <div className="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm">
        <table className="min-w-full divide-y divide-slate-200">
          <thead className="bg-slate-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-500">
                Name
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-500">
                Bonus
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-500">
                Rating
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-500">
                Licensed
              </th>
              <th className="px-6 py-3 text-right text-xs font-medium uppercase tracking-wider text-slate-500">
                Actions
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-200 bg-white">
            {partners.map((partner, index) => (
              <tr key={index}>
                <td className="whitespace-nowrap px-6 py-4 text-sm font-medium text-slate-900">
                  {partner.name}
                </td>
                <td className="px-6 py-4 text-sm text-slate-500">
                  {partner.welcomeBonus}
                </td>
                <td className="px-6 py-4 text-sm text-slate-500">
                  {partner.rating}
                </td>
                <td className="px-6 py-4 text-sm text-slate-500">
                  {partner.licensed ? (
                    <span className="rounded-full bg-green-100 px-2 py-1 text-xs font-medium text-green-800">
                      Yes
                    </span>
                  ) : (
                    <span className="rounded-full bg-red-100 px-2 py-1 text-xs font-medium text-red-800">
                      No
                    </span>
                  )}
                </td>
                <td className="whitespace-nowrap px-6 py-4 text-right text-sm font-medium">
                  <button
                    onClick={() => handleEdit(index)}
                    className="mr-3 text-blue-600 hover:text-blue-900"
                  >
                    Edit
                  </button>
                  <button
                    onClick={() => handleDelete(index)}
                    className="text-red-600 hover:text-red-900"
                  >
                    Delete
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

