"use client";

import { useState } from "react";
import { ArrowLeft, Save, Upload } from "lucide-react";
import { useRouter } from "next/navigation";
import Swal from 'sweetalert2';
import dynamic from 'next/dynamic';

// Currency options - separate codes and symbols
const currencyCodes = [
  { code: "USD", name: "US Dollar" },
  { code: "PKR", name: "Pakistani Rupee" },
  { code: "EUR", name: "Euro" },
  { code: "GBP", name: "British Pound" },
  { code: "AUD", name: "Australian Dollar" },
  { code: "CAD", name: "Canadian Dollar" },
  { code: "AED", name: "UAE Dirham" },
  { code: "SAR", name: "Saudi Riyal" },
  { code: "INR", name: "Indian Rupee" },
  { code: "JPY", name: "Japanese Yen" },
  { code: "CNY", name: "Chinese Yuan" },
  { code: "CHF", name: "Swiss Franc" }
];

const currencySymbols = [
  { symbol: "$", name: "Dollar Sign" },
  { symbol: "Rs", name: "Rupee Sign" },
  { symbol: "€", name: "Euro Sign" },
  { symbol: "£", name: "Pound Sign" },
  { symbol: "A$", name: "Australian Dollar" },
  { symbol: "C$", name: "Canadian Dollar" },
  { symbol: "د.إ", name: "UAE Dirham" },
  { symbol: "﷼", name: "Saudi Riyal" },
  { symbol: "₹", name: "Indian Rupee" },
  { symbol: "¥", name: "Yen/Yuan Sign" },
  { symbol: "₩", name: "Won Sign" },
  { symbol: "₪", name: "Shekel Sign" },
  { symbol: "₺", name: "Turkish Lira" },
  { symbol: "₽", name: "Ruble Sign" },
  { symbol: "₿", name: "Bitcoin Sign" }
];

// Dynamic import for Summernote editor
const SummernoteEditor = dynamic(
  () => import('../../../components/organisms/SummernoteEditor'),
  { 
    ssr: false,
    loading: () => <div className="border rounded-xl p-4 text-center text-gray-500">Loading editor...</div>
  }
);

const AddCountry = () => {
  const router = useRouter();

  const [formData, setFormData] = useState({
    name: "",
    code: "",
    currency: "USD",
    currencySymbol: "$",
    consultationFee: "",
    consultationDiscountFee: "",
    featureImage: "",
    before_description: "",
    after_description: "",
    show_in_menu: true // NEW: Menu visibility field
  });

  const [imagePreview, setImagePreview] = useState(null);
  const [uploading, setUploading] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value
    }));
  };

  const handleBeforeDescriptionChange = (content) => {
    setFormData((prev) => ({
      ...prev,
      before_description: content
    }));
  };

  const handleAfterDescriptionChange = (content) => {
    setFormData((prev) => ({
      ...prev,
      after_description: content
    }));
  };

  const handleImageChange = async (e) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 2 * 1024 * 1024) {
        Swal.fire({
          icon: 'warning',
          title: 'File Too Large',
          text: 'Image size should be less than 2MB. Please choose a smaller image.',
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK'
        });
        return;
      }

      if (!file.type.startsWith('image/')) {
        Swal.fire({
          icon: 'error',
          title: 'Invalid File Type',
          text: 'Please select a valid image file.',
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK'
        });
        return;
      }

      try {
        setUploading(true);
        const formData = new FormData();
        formData.append('image', file);
        formData.append('uploadType', 'countries');

        const uploadResponse = await fetch('/api/internal/upload', {
          method: 'POST',
          body: formData,
        });

        const uploadResult = await uploadResponse.json();

        if (!uploadResponse.ok) {
          throw new Error(uploadResult.message || 'Upload failed');
        }

        setFormData((prev) => ({ ...prev, featureImage: uploadResult.s3Key }));
        setImagePreview(uploadResult.url);
        
        Swal.fire({
          icon: 'success',
          title: 'Image Uploaded!',
          text: 'Image has been uploaded successfully.',
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK',
          timer: 2000,
          showConfirmButton: false
        });
      } catch (error) {
        console.error('Upload error:', error);
        Swal.fire({
          icon: 'error',
          title: 'Upload Failed',
          text: `Upload failed: ${error.message}`,
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK'
        });
      } finally {
        setUploading(false);
      }
    }
  };

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

    // Validate required fields
    if (!formData.name || !formData.code || !formData.currency || !formData.currencySymbol) {
      Swal.fire({
        icon: 'error',
        title: 'Missing Fields',
        text: 'Please fill in all required fields including currency code and symbol.',
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
      return;
    }

    try {
      setSubmitting(true);
      const res = await fetch("/api/internal/countries", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: formData.name,
          code: formData.code,
          currency: formData.currency,
          currencySymbol: formData.currencySymbol,
          consultationFee: formData.consultationFee,
          consultationDiscountFee: formData.consultationDiscountFee,
          featureImage: formData.featureImage,
          before_description: formData.before_description,
          after_description: formData.after_description,
          show_in_menu: formData.show_in_menu, // NEW: Add menu visibility
        }),
      });

      const data = await res.json();

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

      await Swal.fire({
        icon: 'success',
        title: 'Success!',
        text: 'Country added successfully!',
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
      
      router.push("/admin/countries");
    } catch (err) {
      console.error("❌ Submit Error:", err);
      
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: err.message || "Something went wrong. Please try again.",
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="space-y-6 p-4 sm:p-6 bg-gradient-to-br from-green-50 to-teal-100 min-h-screen">
      {/* Header */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center gap-4">
        <button
          onClick={() => router.push("/admin/countries")}
          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 Country</h1>
          <p className="text-gray-600 mt-1">Add a new country to the system</p>
        </div>
      </div>

      {/* Form */}
      <form
        onSubmit={handleSubmit}
        className="bg-white rounded-2xl shadow-xl p-6 sm:p-8 w-full max-w-6xl mx-auto"
      >
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 sm:gap-8">
          {/* Left Column */}
          <div className="space-y-6">
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">
                Country Name <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                name="name"
                value={formData.name}
                onChange={handleChange}
                required
                className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                placeholder="Enter country name"
              />
            </div>
            
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">
                Country Code <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                name="code"
                maxLength={3}
                value={formData.code}
                onChange={handleChange}
                required
                className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                placeholder="e.g., USA"
              />
              <p className="text-xs text-gray-500 mt-1">3-letter country code (e.g., USA, PAK, UAE)</p>
            </div>

            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">
                Consultation Fee <span className="text-red-500">*</span>
              </label>
              <input
                type="number"
                name="consultationFee"
                value={formData.consultationFee}
                onChange={handleChange}
                required
                min="0"
                step="0.01"
                className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                placeholder="0.00"
              />
            </div>
          </div>

          {/* Right Column */}
          <div className="space-y-6">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Currency Code <span className="text-red-500">*</span>
                </label>
                <select
                  name="currency"
                  value={formData.currency}
                  onChange={handleChange}
                  className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  required
                >
                  <option value="">Select Currency Code</option>
                  {currencyCodes.map((currency) => (
                    <option key={currency.code} value={currency.code}>
                      {currency.code} - {currency.name}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  Currency Symbol <span className="text-red-500">*</span>
                </label>
                <select
                  name="currencySymbol"
                  value={formData.currencySymbol}
                  onChange={handleChange}
                  className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  required
                >
                  <option value="">Select Currency Symbol</option>
                  {currencySymbols.map((symbol) => (
                    <option key={symbol.symbol} value={symbol.symbol}>
                      {symbol.symbol} - {symbol.name}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">Discount Fee</label>
              <input
                type="number"
                name="consultationDiscountFee"
                value={formData.consultationDiscountFee}
                onChange={handleChange}
                min="0"
                step="0.01"
                className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                placeholder="0.00"
              />
            </div>

            {/* NEW: Menu Visibility Field */}
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">
                Show in Menu
              </label>
              <select
                name="show_in_menu"
                value={formData.show_in_menu ? "1" : "0"}
                onChange={(e) => setFormData(prev => ({
                  ...prev,
                  show_in_menu: e.target.value === "1"
                }))}
                className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              >
                <option value="1">Yes</option>
                <option value="0">No</option>
              </select>
              <p className="text-xs text-gray-500 mt-1">Show this country in navigation menu</p>
            </div>

            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">Feature Image</label>
              <div className="border-2 border-dashed border-gray-300 rounded-xl p-4 sm:p-6 text-center hover:border-gray-400 transition-colors">
                {uploading ? (
                  <div className="text-center">
                    <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-[#0B6D76] mx-auto mb-2"></div>
                    <p className="text-sm text-gray-600">Uploading image...</p>
                  </div>
                ) : imagePreview ? (
                  <div>
                    <img
                      src={imagePreview}
                      alt="Preview"
                      className="w-20 h-20 sm:w-24 sm:h-24 object-cover rounded-lg mx-auto mb-2"
                    />
                    <p className="text-xs text-green-600 mb-2">✓ Image uploaded successfully</p>
                    <button
                      type="button"
                      onClick={() => {
                        setFormData(prev => ({ ...prev, featureImage: "" }));
                        setImagePreview(null);
                      }}
                      className="text-xs text-red-600 hover:text-red-800"
                    >
                      Remove Image
                    </button>
                  </div>
                ) : (
                  <>
                    <Upload className="w-10 h-10 text-gray-400 mx-auto mb-2" />
                    <p className="text-sm text-gray-600 mb-2">Click to upload an image</p>
                  </>
                )}
                <input
                  type="file"
                  accept="image/*"
                  onChange={handleImageChange}
                  className="mt-2 text-xs sm:text-sm mx-auto"
                  disabled={uploading}
                />
                {!uploading && !imagePreview && (
                  <p className="text-xs text-gray-500 mt-2">Supported formats: JPG, PNG, WebP (max 2MB)</p>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Description Editors - Full Width */}
        <div className="mt-6 sm:mt-8 pt-6 sm:pt-8 border-t">
          {/* Before Description Editor */}
          <div className="mb-8">
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Before Content Description
            </label>
            <p className="text-xs text-gray-500 mb-4">
              This content will appear before the main country information. Use this for introductory content, overview, or key highlights.
            </p>
            <SummernoteEditor
              value={formData.before_description}
              onChange={handleBeforeDescriptionChange}
              height={300}
              placeholder="Enter introductory content that appears before the main country information..."
            />
          </div>

          {/* After Description Editor */}
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              After Content Description
            </label>
            <p className="text-xs text-gray-500 mb-4">
              This content will appear after the main country information. Use this for additional details, conclusion, or supplementary information.
            </p>
            <SummernoteEditor
              value={formData.after_description}
              onChange={handleAfterDescriptionChange}
              height={300}
              placeholder="Enter additional content that appears after the main country information..."
            />
          </div>
        </div>

        {/* Submit Button */}
        <div className="flex justify-end mt-6 sm:mt-8 pt-6 sm:pt-8 border-t">
          <button
            type="submit"
            disabled={submitting || uploading}
            className={`px-6 sm:px-8 py-3 rounded-xl flex items-center gap-2 transition-all ${
              submitting || uploading
                ? 'bg-gray-400 cursor-not-allowed'
                : 'bg-[#0B6D76] text-white hover:bg-[#09545c] hover:shadow-xl'
            }`}
          >
            {submitting ? (
              <>
                <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                <span>Adding Country...</span>
              </>
            ) : (
              <>
                <Save className="w-5 h-5" />
                <span>Add Country</span>
              </>
            )}
          </button>
        </div>
      </form>
    </div>
  );
};

export default AddCountry;