"use client";

import { useState, useEffect } from "react";
import { ArrowLeft, Save, Plus, Link as LinkIcon, ExternalLink, RefreshCw } from "lucide-react";
import { useRouter } from "next/navigation";
import Swal from 'sweetalert2';

const AddRedirect = () => {
  const router = useRouter();
  
  const [formData, setFormData] = useState({
    source_path: "",
    destination_path: "",
    redirect_type: "301",
    is_active: true
  });

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

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
    
    // Clear validation error for this field
    if (validationErrors[name]) {
      setValidationErrors(prev => ({
        ...prev,
        [name]: undefined
      }));
    }
  };

  const validateForm = () => {
    const errors = {};
    
    // Source path validation
    if (!formData.source_path.trim()) {
      errors.source_path = "Source path is required";
    } else if (!formData.source_path.startsWith('/')) {
      errors.source_path = "Source path must start with '/'";
    }
    
    // Destination path validation
    if (!formData.destination_path.trim()) {
      errors.destination_path = "Destination path is required";
    } else if (!formData.destination_path.startsWith('/') && 
               !formData.destination_path.startsWith('http://') && 
               !formData.destination_path.startsWith('https://')) {
      errors.destination_path = "Destination must start with '/', 'http://', or 'https://'";
    }
    
    // Circular redirect validation
    if (formData.source_path === formData.destination_path) {
      errors.destination_path = "Source and destination cannot be the same";
    }
    
    return errors;
  };

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

    // Validate form
    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 res = await fetch("/api/internal/redirects", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...formData,
          redirect_type: parseInt(formData.redirect_type),
          is_active: formData.is_active ? 1 : 0
        }),
      });

      const data = await res.json();

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

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

  return (
    <div className="p-6 bg-gradient-to-br from-blue-50 to-cyan-100 min-h-screen">
      {/* Header */}
      <div className="flex items-center gap-4 mb-6">
        <button
          onClick={() => router.push("/admin/redirects")}
          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">Add New Redirect</h1>
          <p className="text-gray-600 mt-1">Create a new URL redirect rule</p>
        </div>
      </div>

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

        {/* Destination Path */}
        <div className="mb-6">
          <label className="block text-sm font-semibold text-gray-700 mb-2">
            Destination Path <span className="text-red-500">*</span>
          </label>
          <div className="relative">
            <ExternalLink className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="text"
              name="destination_path"
              value={formData.destination_path}
              onChange={handleChange}
              required
              className={`w-full pl-10 pr-4 py-3 border ${validationErrors.destination_path ? 'border-red-300' : 'border-gray-300'} rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent`}
              placeholder="/new-page or https://example.com/page"
            />
          </div>
          {validationErrors.destination_path && (
            <p className="text-red-500 text-sm mt-1">{validationErrors.destination_path}</p>
          )}
          <p className="text-xs text-gray-500 mt-1">
            Where users should be redirected to. Can be a relative path starting with / or a full URL starting with http:// or https://.
          </p>
        </div>

        {/* Redirect Type */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Redirect Type <span className="text-red-500">*</span>
            </label>
            <select
              name="redirect_type"
              value={formData.redirect_type}
              onChange={handleChange}
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent"
            >
              <option value="301">301 Permanent Redirect</option>
              <option value="302">302 Temporary Redirect</option>
            </select>
            <div className="mt-2 text-sm text-gray-600">
              <div className="flex items-center gap-2 mb-1">
                <span className="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full">301</span>
                <span>Permanent - SEO friendly, transfers ranking power</span>
              </div>
              <div className="flex items-center gap-2">
                <span className="px-2 py-1 bg-yellow-100 text-yellow-800 text-xs rounded-full">302</span>
                <span>Temporary - For short-term changes</span>
              </div>
            </div>
          </div>

          {/* Active Status */}
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">Status</label>
            <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">
                  Active Redirect
                </label>
                <p className="text-xs text-gray-500 mt-1">
                  When active, the redirect will be applied to incoming requests.
                </p>
              </div>
            </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="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="bg-white p-3 rounded-lg border">
                <div className="text-xs text-gray-500 mb-1">Source</div>
                <div className="font-mono text-sm truncate">
                  <span className="text-gray-400">https://yourdomain.com</span>
                  <span className="text-gray-900">{formData.source_path || "/example"}</span>
                </div>
              </div>
              <div className="bg-white p-3 rounded-lg border">
                <div className="text-xs text-gray-500 mb-1">Destination</div>
                <div className="font-mono text-sm truncate">
                  {formData.destination_path.startsWith('http') ? (
                    <span className="text-blue-600">{formData.destination_path || "https://example.com"}</span>
                  ) : (
                    <>
                      <span className="text-gray-400">https://yourdomain.com</span>
                      <span className="text-blue-600">{formData.destination_path || "/example"}</span>
                    </>
                  )}
                </div>
              </div>
            </div>
            <div className="mt-3 text-center">
              <div className="inline-flex items-center gap-2 text-sm text-gray-600">
                <div className={`px-2 py-1 rounded-full text-xs font-medium ${
                  formData.redirect_type === "301" 
                    ? 'bg-blue-100 text-blue-800' 
                    : 'bg-yellow-100 text-yellow-800'
                }`}>
                  {formData.redirect_type === "301" ? "301 Permanent" : "302 Temporary"}
                </div>
                <span>→</span>
                <div className={`px-2 py-1 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>

        {/* 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>Adding Redirect...</span>
              </>
            ) : (
              <>
                <Save className="w-5 h-5" />
                <span>Add Redirect</span>
              </>
            )}
          </button>
        </div>
      </form>
    </div>
  );
};

export default AddRedirect;