"use client";

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

interface SiteInfoTabProps {
  readonly siteInfo: SiteInfo | null;
  readonly onUpdate: () => void | Promise<void>;
}

export function SiteInfoTab({ siteInfo, onUpdate }: SiteInfoTabProps) {
  const [formData, setFormData] = useState<SiteInfo>({
    siteName: "",
    siteLogo: "",
    email: "",
    address: "",
    phone: "",
    accountCode: "",
    tagline: "",
    favicon: "",
    browserTitle: "",
  });
  const [uploadingLogo, setUploadingLogo] = useState(false);
  const [uploadingFavicon, setUploadingFavicon] = useState(false);

  useEffect(() => {
    if (siteInfo) {
      setFormData(siteInfo);
    }
  }, [siteInfo]);

  const handleSave = async () => {
    try {
      const res = await fetch("/api/admin/siteinfo", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 
          siteInfo: formData,
          oldSiteLogo: siteInfo?.siteLogo,
          oldFavicon: siteInfo?.favicon
        }),
      });
      
      if (res.ok) {
        const data = await res.json();
        // Update formData with the response data immediately
        if (data.siteInfo) {
          setFormData(data.siteInfo);
        }
        // Reload data from server to ensure consistency
        // onUpdate may be async, so we await it
        await Promise.resolve(onUpdate());
        alert("Site info updated successfully! Refreshing page to show changes in header/footer...");
        // Force a page refresh to ensure Header/Footer in root layout re-render with fresh data
        // This is especially important for subdomain deployments (admin.trustrank.live)
        setTimeout(() => {
          window.location.reload();
        }, 500);
      } else {
        const errorData = await res.json().catch(() => ({}));
        alert(`Failed to update site info: ${errorData.error || 'Unknown error'}`);
      }
    } catch (error) {
      console.error('Save error:', error);
      alert("Failed to update site info");
    }
  };

  if (!siteInfo) {
    return <div>Loading...</div>;
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between">
        <h2 className="text-2xl font-bold text-slate-900">Site Information</h2>
        <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 Changes
        </button>
      </div>

      <div className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
        <div className="grid gap-6 sm:grid-cols-2">
          <div>
            <label className="block text-sm font-medium text-slate-700">
              Site Name
            </label>
            <input
              type="text"
              value={formData.siteName}
              onChange={(e) =>
                setFormData({ ...formData, siteName: 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">
              Site 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', 'site');
                    // Pass old logo path if exists
                    if (formData.siteLogo) {
                      uploadFormData.append('oldPath', formData.siteLogo);
                    }
                    
                    try {
                      const res = await fetch('/api/admin/upload', {
                        method: 'POST',
                        body: uploadFormData,
                      });
                      const data = await res.json();
                      if (data.success) {
                        setFormData({ ...formData, siteLogo: 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.siteLogo}
                onChange={(e) =>
                  setFormData({ ...formData, siteLogo: 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="/logo.png"
              />
            </div>
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700">
              Email
            </label>
            <input
              type="email"
              value={formData.email}
              onChange={(e) =>
                setFormData({ ...formData, email: 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">
              Phone
            </label>
            <input
              type="text"
              value={formData.phone}
              onChange={(e) =>
                setFormData({ ...formData, phone: 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">
              Address
            </label>
            <input
              type="text"
              value={formData.address}
              onChange={(e) =>
                setFormData({ ...formData, address: 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">
              Account Code
            </label>
            <input
              type="text"
              value={formData.accountCode}
              onChange={(e) =>
                setFormData({ ...formData, accountCode: 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">
              Tagline (Header & Homepage)
            </label>
            <input
              type="text"
              value={formData.tagline}
              onChange={(e) =>
                setFormData({ ...formData, tagline: 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"
              placeholder="Top-Rated UK Betting Platforms"
            />
            <p className="mt-1 text-xs text-slate-500">
              This appears in the header subtitle and homepage heading
            </p>
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700">
              Browser Title
            </label>
            <input
              type="text"
              value={formData.browserTitle}
              onChange={(e) =>
                setFormData({ ...formData, browserTitle: 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"
              placeholder="Top-Rated UK Betting Platforms"
            />
            <p className="mt-1 text-xs text-slate-500">
              This appears in the browser tab
            </p>
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700">
              Favicon
            </label>
            <div className="mt-1 space-y-2">
              <div className="relative">
              <input
                type="file"
                accept="image/*,.ico"
                  disabled={uploadingFavicon}
                onChange={async (e) => {
                  const file = e.target.files?.[0];
                  if (file) {
                      setUploadingFavicon(true);
                    const uploadFormData = new FormData();
                    uploadFormData.append('file', file);
                    uploadFormData.append('type', 'favicon');
                    // Pass old favicon path if exists
                    if (formData.favicon) {
                      uploadFormData.append('oldPath', formData.favicon);
                    }
                    
                    try {
                      const res = await fetch('/api/admin/upload', {
                        method: 'POST',
                        body: uploadFormData,
                      });
                      const data = await res.json();
                      if (data.success) {
                        setFormData({ ...formData, favicon: data.path });
                      } else {
                        alert('Failed to upload favicon');
                      }
                    } catch (error) {
                      alert('Failed to upload favicon');
                      } finally {
                        setUploadingFavicon(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"
              />
                {uploadingFavicon && (
                  <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.favicon}
                onChange={(e) =>
                  setFormData({ ...formData, favicon: 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="/favicon.ico"
              />
            </div>
            <p className="mt-1 text-xs text-slate-500">
              Upload a .ico, .png, or .svg file for the browser favicon
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

