"use client";

import { useState, useEffect } from "react";
import { useParams, useRouter } from "next/navigation";
import { ArrowLeft, Save, Globe, Calendar, BarChart } from "lucide-react";
import Swal from 'sweetalert2';

const EditSitemapUrl = () => {
  const router = useRouter();
  const params = useParams();
  const id = params.id;
  
  const [formData, setFormData] = useState({
    url_path: "",
    priority: "0.5",
    last_modified: "",
    is_active: true
  });

  const [loading, setLoading] = useState(false);
  const [fetching, setFetching] = useState(true);
  const [validationErrors, setValidationErrors] = useState({});

  useEffect(() => {
    if (id) {
      fetchSitemapData();
    }
  }, [id]);

  const fetchSitemapData = async () => {
    try {
      const res = await fetch(`/api/internal/sitemap?id=${id}`, { method: "PATCH"});
      if (!res.ok) throw new Error("Failed to fetch sitemap URL");
      
      const data = await res.json();
      
      if (data.success && data.data) {
        const url = data.data;
        
        setFormData({
          url_path: url.url_path || "",
          priority: url.priority?.toString() || "0.5",
          last_modified: url.last_modified ? url.last_modified.split('T')[0] : "",
          is_active: url.is_active !== 0,
        });
      } else {
        throw new Error(data.error || "Failed to load sitemap data");
      }
    } catch (error) {
      console.error('Error fetching sitemap URL:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: error.message || 'Failed to load sitemap data',
      });
      router.push("/admin/sitemap");
    } finally {
      setFetching(false);
    }
  };

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : (name === 'priority' ? parseFloat(value) : value)
    }));
    
    if (validationErrors[name]) {
      setValidationErrors(prev => ({
        ...prev,
        [name]: undefined
      }));
    }
  };

  const validateForm = () => {
    const errors = {};
    
    if (!formData.url_path.trim()) {
      errors.url_path = "URL path is required";
    } else if (!formData.url_path.startsWith('/')) {
      errors.url_path = "URL path must start with '/'";
    }
    
    if (formData.priority < 0 || formData.priority > 1) {
      errors.priority = "Priority must be between 0.0 and 1.0";
    }
    
    if (formData.last_modified && isNaN(new Date(formData.last_modified).getTime())) {
      errors.last_modified = "Invalid date format";
    }
    
    return errors;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (loading) return;

    const errors = validateForm();
    if (Object.keys(errors).length > 0) {
      setValidationErrors(errors);
      Swal.fire({
        icon: 'error',
        title: 'Validation Error',
        html: Object.values(errors).map(error => `<p>• ${error}</p>`).join(''),
        confirmButtonColor: '#0B6D76',
      });
      return;
    }

    try {
      setLoading(true);
      
      const submitData = {
        ...formData,
        priority: parseFloat(formData.priority),
        is_active: formData.is_active ? 1 : 0,
        last_modified: formData.last_modified || null
      };

      const res = await fetch(`/api/internal/sitemap?id=${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(submitData),
      });

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.error || "Failed to update URL");
      }

      await Swal.fire({
        icon: 'success',
        title: 'Success!',
        text: 'Sitemap URL updated successfully!',
        confirmButtonColor: '#0B6D76',
      });
      
      router.push("/admin/sitemap");
    } catch (err) {
      console.error("Update Error:", err);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: err.message || "Something went wrong.",
        confirmButtonColor: '#0B6D76',
      });
    } finally {
      setLoading(false);
    }
  };

  const getPriorityColor = (priority) => {
    if (priority >= 0.8) return 'text-red-600';
    if (priority >= 0.5) return 'text-yellow-600';
    return 'text-blue-600';
  };

  if (fetching) {
    return (
      <div className="p-6 bg-gradient-to-br from-green-50 to-emerald-100 min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#217484]"></div>
      </div>
    );
  }

  return (
    <div className="p-6 bg-gradient-to-br from-green-50 to-emerald-100 min-h-screen">
      {/* Header */}
      <div className="flex items-center gap-4 mb-6">
        <button
          onClick={() => router.push("/admin/sitemap")}
          className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
        >
          <ArrowLeft className="w-6 h-6 text-gray-600" />
        </button>
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold text-gray-900">Edit Sitemap URL</h1>
          <p className="text-gray-600 mt-1">Update sitemap URL details</p>
        </div>
      </div>

      {/* Form */}
      <form onSubmit={handleSubmit} className="bg-white rounded-2xl shadow-xl p-6 sm:p-8 max-w-3xl mx-auto">
        {/* URL Path */}
        <div className="mb-6">
          <label className="block text-sm font-semibold text-gray-700 mb-2">
            URL Path <span className="text-red-500">*</span>
          </label>
          <div className="relative">
            <Globe className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="text"
              name="url_path"
              value={formData.url_path}
              onChange={handleChange}
              required
              className={`w-full pl-10 pr-4 py-3 border ${validationErrors.url_path ? 'border-red-300' : 'border-gray-300'} rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent`}
              placeholder="/about or /products/item-1"
            />
          </div>
          {validationErrors.url_path && (
            <p className="text-red-500 text-sm mt-1">{validationErrors.url_path}</p>
          )}
          <p className="text-xs text-gray-500 mt-1">
            The URL path that will be included in the sitemap. Must start with /.
          </p>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
          {/* Priority */}
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Priority <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <BarChart className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
              <select
                name="priority"
                value={formData.priority}
                onChange={handleChange}
                className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent"
              >
                <option value="1.0">1.0 - Highest</option>
                <option value="0.9">0.9 - Very High</option>
                <option value="0.8">0.8 - High</option>
                <option value="0.7">0.7 - Medium High</option>
                <option value="0.6">0.6 - Medium</option>
                <option value="0.5">0.5 - Normal</option>
                <option value="0.4">0.4 - Low Medium</option>
                <option value="0.3">0.3 - Low</option>
                <option value="0.2">0.2 - Very Low</option>
                <option value="0.1">0.1 - Lowest</option>
                <option value="0.0">0.0 - Ignore</option>
              </select>
            </div>
            {validationErrors.priority && (
              <p className="text-red-500 text-sm mt-1">{validationErrors.priority}</p>
            )}
            <div className="mt-2">
              <div className="flex items-center justify-between text-sm text-gray-600">
                <span>Importance:</span>
                <span className={`font-medium ${getPriorityColor(parseFloat(formData.priority))}`}>
                  {formData.priority >= 0.8 ? 'High' : formData.priority >= 0.5 ? 'Medium' : 'Low'}
                </span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-2 mt-1">
                <div 
                  className="bg-[#217484] h-2 rounded-full" 
                  style={{ width: `${parseFloat(formData.priority) * 100}%` }}
                ></div>
              </div>
            </div>
          </div>

          {/* Last Modified */}
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Last Modified
            </label>
            <div className="relative">
              <Calendar className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                type="date"
                name="last_modified"
                value={formData.last_modified}
                onChange={handleChange}
                className={`w-full pl-10 pr-4 py-3 border ${validationErrors.last_modified ? 'border-red-300' : 'border-gray-300'} rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent`}
              />
            </div>
            {validationErrors.last_modified && (
              <p className="text-red-500 text-sm mt-1">{validationErrors.last_modified}</p>
            )}
            <p className="text-xs text-gray-500 mt-1">
              When this page was last updated. Leave empty for current date.
            </p>
          </div>
        </div>

        {/* Active Status */}
        <div className="mb-6">
          <div className="flex items-center gap-3 p-4 border border-gray-200 rounded-xl bg-gray-50">
            <input
              type="checkbox"
              name="is_active"
              id="is_active"
              checked={formData.is_active}
              onChange={handleChange}
              className="w-5 h-5 text-[#217484] rounded focus:ring-[#217484]"
            />
            <div>
              <label htmlFor="is_active" className="text-sm font-medium text-gray-700">
                Include in Sitemap
              </label>
              <p className="text-xs text-gray-500 mt-1">
                When active, this URL will be included in the generated sitemap.xml
              </p>
            </div>
          </div>
        </div>

        {/* Preview Section */}
        <div className="mb-6">
          <label className="block text-sm font-semibold text-gray-700 mb-2">Preview</label>
          <div className="bg-gray-50 border border-gray-200 rounded-xl p-4">
            <div className="space-y-3">
              <div className="bg-white p-3 rounded-lg border">
                <div className="text-xs text-gray-500 mb-1">Full URL</div>
                <div className="font-mono text-sm">
                  <span className="text-gray-400">https://yourdomain.com</span>
                  <span className="text-gray-900">{formData.url_path || "/example"}</span>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="bg-white p-3 rounded-lg border">
                  <div className="text-xs text-gray-500 mb-1">Priority</div>
                  <div className="flex items-center gap-2">
                    <span className={`px-2 py-1 rounded-full text-xs font-medium ${getPriorityColor(parseFloat(formData.priority)).replace('text', 'bg')}`}>
                      {formData.priority >= 0.8 ? 'High' : formData.priority >= 0.5 ? 'Medium' : 'Low'}
                    </span>
                    <span className="text-sm font-medium">{formData.priority}</span>
                  </div>
                </div>
                <div className="bg-white p-3 rounded-lg border">
                  <div className="text-xs text-gray-500 mb-1">Status</div>
                  <div className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                    formData.is_active 
                      ? 'bg-green-100 text-green-800' 
                      : 'bg-gray-100 text-gray-800'
                  }`}>
                    {formData.is_active ? 'Active' : 'Inactive'}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Submit Button */}
        <div className="flex justify-end mt-8 pt-6 border-t">
          <button
            type="submit"
            disabled={loading}
            className={`px-8 py-3 rounded-xl flex items-center gap-2 transition-all ${
              loading
                ? 'bg-gray-400 cursor-not-allowed'
                : 'bg-[#217484] text-white hover:bg-[#1a5d6b] hover:shadow-xl'
            }`}
          >
            {loading ? (
              <>
                <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                <span>Updating URL...</span>
              </>
            ) : (
              <>
                <Save className="w-5 h-5" />
                <span>Update URL</span>
              </>
            )}
          </button>
        </div>
      </form>
    </div>
  );
};

export default EditSitemapUrl;