import React, { useState, useEffect } from "react";
import { X, Globe, Plus, Edit3 } from "lucide-react";
import { ClientSite } from "../types";
import { normalizeUrl } from "../../backend/validation";

interface AddSiteModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (site: Partial<ClientSite>) => Promise<void>;
  initialSite?: ClientSite | null;
}

export const AddSiteModal: React.FC<AddSiteModalProps> = ({
  isOpen,
  onClose,
  onSave,
  initialSite,
}) => {
  const [name, setName] = useState("");
  const [url, setUrl] = useState("");
  const [clientName, setClientName] = useState("");
  const [clientPhone, setClientPhone] = useState("");
  const [clientEmail, setClientEmail] = useState("");
  const [packageType, setPackageType] =
    useState<ClientSite["packageType"]>("care_plan");
  const [category, setCategory] = useState<ClientSite["category"]>("corporate");
  const [hostingProvider, setHostingProvider] = useState("");
  const [notes, setNotes] = useState("");
  const [restApiUrl, setRestApiUrl] = useState(""),
    [domainRenewalDate, setDomainRenewalDate] = useState(""),
    [hostingRenewalDate, setHostingRenewalDate] = useState(""),
    [maintenanceUntil, setMaintenanceUntil] = useState(""),
    [error, setError] = useState(""),
    [saving, setSaving] = useState(false);

  useEffect(() => {
    setError("");
    setRestApiUrl(initialSite?.restApiUrl || "");
    setDomainRenewalDate(initialSite?.domainRenewalDate || "");
    setHostingRenewalDate(initialSite?.hostingRenewalDate || "");
    const d = initialSite?.maintenanceUntil
      ? new Date(initialSite.maintenanceUntil)
      : null;
    setMaintenanceUntil(
      d
        ? new Date(d.getTime() - d.getTimezoneOffset() * 60000)
            .toISOString()
            .slice(0, 16)
        : "",
    );
    if (initialSite) {
      setName(initialSite.name);
      setUrl(initialSite.url);
      setClientName(initialSite.clientName);
      setClientPhone(initialSite.clientPhone || "");
      setClientEmail(initialSite.clientEmail || "");
      setPackageType(initialSite.packageType);
      setCategory(initialSite.category);
      setHostingProvider(initialSite.hostingProvider || "");
      setNotes(initialSite.notes || "");
    } else {
      setName("");
      setUrl("");
      setClientName("");
      setClientPhone("");
      setClientEmail("");
      setPackageType("care_plan");
      setCategory("corporate");
      setHostingProvider("");
      setNotes("");
    }
  }, [initialSite, isOpen]);

  if (!isOpen) return null;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim() || !url.trim()) return;

    setError("");
    setSaving(true);
    try {
      const cleanUrl = normalizeUrl(url);
      await onSave({
        id: initialSite ? initialSite.id : `site-${Date.now()}`,
        name: name.trim(),
        url: cleanUrl,
        clientName: clientName.trim() || "Klien",
        clientPhone: clientPhone.trim() || undefined,
        clientEmail: clientEmail.trim() || undefined,
        packageType,
        category,
        hostingProvider: hostingProvider.trim() || undefined,
        notes: notes.trim() || undefined,
        restApiUrl: restApiUrl.trim() ? normalizeUrl(restApiUrl) : undefined,
        domainRenewalDate: domainRenewalDate || undefined,
        hostingRenewalDate: hostingRenewalDate || undefined,
        maintenanceUntil: maintenanceUntil
          ? new Date(maintenanceUntil).toISOString()
          : undefined,
      });

      onClose();
    } catch (e) {
      setError((e as Error).message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-sm overflow-y-auto">
      <div className="relative w-full max-w-lg bg-slate-900 border border-slate-800 rounded-2xl shadow-2xl overflow-hidden my-8 animate-in fade-in zoom-in-95 duration-150">
        {/* Header */}
        <div className="p-5 border-b border-slate-800 flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <div className="p-2 rounded-lg bg-blue-500/20 text-blue-400">
              {initialSite ? (
                <Edit3 className="w-5 h-5" />
              ) : (
                <Plus className="w-5 h-5" />
              )}
            </div>
            <div>
              <h2 className="text-base font-bold text-white">
                {initialSite
                  ? "Kemaskini Laman Web Klien"
                  : "Tambah Laman Web WordPress Klien"}
              </h2>
              <p className="text-xs text-slate-400">
                Semakan website, SSL dan ralat melalui server pemantau
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-1.5 text-slate-400 hover:text-white hover:bg-slate-800 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Form */}
        <form
          onSubmit={handleSubmit}
          className="p-5 space-y-4 max-h-[75vh] overflow-y-auto"
        >
          <div>
            <label
              htmlFor="site-name"
              className="block text-xs font-medium text-slate-300 mb-1"
            >
              Nama Laman Web / Bisnes <span className="text-red-400">*</span>
            </label>
            <input
              type="text"
              maxLength={160}
              required
              placeholder="Contoh: Butik Bella Hijab, Klinik Dr. Azman"
              id="site-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-sm text-white placeholder-slate-500 focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
            />
          </div>

          <div>
            <label
              htmlFor="site-url"
              className="block text-xs font-medium text-slate-300 mb-1"
            >
              URL Laman Web WordPress <span className="text-red-400">*</span>
            </label>
            <div className="relative">
              <input
                type="text"
                required
                placeholder="https://clientdomain.com"
                id="site-url"
                value={url}
                onChange={(e) => setUrl(e.target.value)}
                className="w-full pl-9 pr-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-sm text-white font-mono placeholder-slate-500 focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
              />
              <Globe className="w-4 h-4 text-slate-500 absolute left-3 top-2.5" />
            </div>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div>
              <label
                htmlFor="site-clientName"
                className="block text-xs font-medium text-slate-300 mb-1"
              >
                Nama Klien / Syarikat
              </label>
              <input
                type="text"
                placeholder="Nama pemilik web"
                id="site-clientName"
                value={clientName}
                onChange={(e) => setClientName(e.target.value)}
                className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-sm text-white placeholder-slate-500 focus:outline-none focus:border-blue-500"
              />
            </div>

            <div>
              <label
                htmlFor="site-clientPhone"
                className="block text-xs font-medium text-slate-300 mb-1"
              >
                No Telefon / WhatsApp Klien
              </label>
              <input
                type="text"
                placeholder="012-3456789"
                id="site-clientPhone"
                value={clientPhone}
                onChange={(e) => setClientPhone(e.target.value)}
                className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-sm text-white placeholder-slate-500 focus:outline-none focus:border-blue-500"
              />
            </div>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div>
              <label
                htmlFor="site-packageType"
                className="block text-xs font-medium text-slate-300 mb-1"
              >
                Pakej Penyelenggaraan
              </label>
              <select
                id="site-packageType"
                value={packageType}
                onChange={(e) => setPackageType(e.target.value as any)}
                className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-sm text-white focus:outline-none focus:border-blue-500"
              >
                <option value="care_plan">Care Plan (Bulanan)</option>
                <option value="hosting_only">Hosting Sahaja</option>
                <option value="standard">Standard Web</option>
                <option value="vip">VIP Support 24/7</option>
              </select>
            </div>

            <div>
              <label
                htmlFor="site-category"
                className="block text-xs font-medium text-slate-300 mb-1"
              >
                Jenis Laman Web
              </label>
              <select
                id="site-category"
                value={category}
                onChange={(e) => setCategory(e.target.value as any)}
                className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-sm text-white focus:outline-none focus:border-blue-500"
              >
                <option value="corporate">Korporat / Bisnes</option>
                <option value="ecommerce">E-Commerce (WooCommerce)</option>
                <option value="landing_page">Landing Page</option>
                <option value="portal">Portal / Komuniti</option>
              </select>
            </div>
          </div>

          <div>
            <label
              htmlFor="site-hostingProvider"
              className="block text-xs font-medium text-slate-300 mb-1"
            >
              Hosting Provider (Pilihan)
            </label>
            <input
              type="text"
              placeholder="Contoh: cPanel Hostinger, RunCloud, ServerFreak"
              id="site-hostingProvider"
              value={hostingProvider}
              onChange={(e) => setHostingProvider(e.target.value)}
              className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-sm text-white placeholder-slate-500 focus:outline-none focus:border-blue-500"
            />
          </div>

          <div>
            <label
              htmlFor="site-notes"
              className="block text-xs font-medium text-slate-300 mb-1"
            >
              Nota Tambahan (Pilihan)
            </label>
            <textarea
              rows={2}
              placeholder="Nota kerja, PIC atau rujukan projek. Jangan simpan kata laluan di sini."
              id="site-notes"
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-sm text-white placeholder-slate-500 focus:outline-none focus:border-blue-500"
            />
          </div>

          <label className="block text-xs text-slate-300">
            Emel client
            <input
              type="email"
              value={clientEmail}
              onChange={(e) => setClientEmail(e.target.value)}
              className="block w-full p-2 mt-1 bg-slate-800 border border-slate-700 rounded-lg"
            />
          </label>
          <div className="grid grid-cols-2 gap-3">
            <label className="text-xs">
              Renew domain
              <input
                type="date"
                value={domainRenewalDate}
                onChange={(e) => setDomainRenewalDate(e.target.value)}
                className="w-full p-2 mt-1 bg-slate-800 rounded-lg"
              />
            </label>
            <label className="text-xs">
              Renew hosting
              <input
                type="date"
                value={hostingRenewalDate}
                onChange={(e) => setHostingRenewalDate(e.target.value)}
                className="w-full p-2 mt-1 bg-slate-800 rounded-lg"
              />
            </label>
          </div>
          <label className="block text-xs">
            URL REST API (pilihan)
            <input
              type="text"
              value={restApiUrl}
              onChange={(e) => setRestApiUrl(e.target.value)}
              placeholder="https://domain.com/staging/wp-json/"
              className="block w-full p-2 mt-1 bg-slate-800 rounded-lg"
            />
            <span className="block text-slate-500 mt-1">
              Isi jika URL yang dipantau bukan halaman utama WordPress.
            </span>
          </label>
          <label className="block text-xs">
            Senyapkan alert sehingga (waktu komputer ini)
            <input
              type="datetime-local"
              value={maintenanceUntil}
              onChange={(e) => setMaintenanceUntil(e.target.value)}
              className="block w-full p-2 mt-1 bg-slate-800 rounded-lg"
            />
            <span className="block text-slate-500 mt-1">
              Semakan tetap berjalan. Kosongkan untuk aktifkan alert.
            </span>
          </label>
          {error && (
            <p
              role="alert"
              className="text-sm text-red-300 bg-red-950/50 p-3 rounded-lg"
            >
              {error}
            </p>
          )}
          <div className="pt-3 border-t border-slate-800 flex items-center justify-end space-x-2">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-medium transition-colors"
            >
              Batal
            </button>
            <button
              type="submit"
              disabled={saving}
              className="px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-500 text-white text-xs font-medium transition-colors shadow-sm"
            >
              {saving
                ? "Menyimpan..."
                : initialSite
                  ? "Simpan Perubahan"
                  : "Tambah & Semak"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};
