// app/components/admin/websites/WebsiteForm.tsx
'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import dynamic from 'next/dynamic';

import FormCard from '@/app/components/admin/CommonComponents/Formcard';
import FormSection from '@/app/components/admin/CommonComponents/Formsection';
import FormField from '@/app/components/admin/CommonComponents/Formfield';
import FormSelect, { SelectOption } from '@/app/components/admin/CommonComponents/Formselect';
import FormActions from '@/app/components/admin/CommonComponents/Formactions';
import ImageUpload from '@/app/components/admin/CommonComponents/Imageupload';
import JsonSchemaManager from '@/app/components/admin/CommonComponents/Jsonschemamanager';

const RichTextEditor = dynamic(
  () => import('@/app/components/admin/text-editor/RichTextEditor'),
  {
    ssr: false,
    loading: () => <div className="h-32 bg-var-surface-hover animate-pulse rounded-lg" />,
  }
);

interface Category {
  id: string;
  name: string;
  slug: string;
  category_type: 'GENERAL' | 'SPECIAL';
  status: boolean;
}

interface User {
  id: string;
  email: string;
  display_name: string;
  first_name: string;
  last_name: string;
}

interface NichePricing {
  [key: string]: number;
}

interface WebsiteFormData {
  name: string;
  slug: string;
  domain: string;
  da: number | null;
  dr: number | null;
  traffic: string;
  spam_score: number | null;
  backlinks: number | null;
  link_type: 'Dofollow' | 'Nofollow';
  base_price: number;
  sale_price: number | null;
  content_service_price: number;
  category_id: string;
  user_id: string;
  niches: string[];
  niche_pricing: NichePricing;
  description: string;
  meta_title: string;
  meta_description: string;
  is_indexable: boolean;
  schemas: unknown[];
  status: 'active' | 'inactive' | 'sold_out';
  featured: boolean;
  featured_image: string;
  featured_image_alt_text: string;
}

interface Website extends WebsiteFormData {
  id: string;
  category_name?: string;
  category_slug?: string;
  user_name?: string;
  user_email?: string;
  created_at: string;
  updated_at: string;
}

interface WebsiteFormProps {
  websiteId?: string;
  initialData?: Website;
}

const generateSlug = (name: string) =>
  name
    .toLowerCase()
    .replace(/[^\w\s]/gi, '')
    .replace(/\s+/g, '-')
    .trim();

const EMPTY_FORM: WebsiteFormData = {
  name: '',
  slug: '',
  domain: '',
  da: null,
  dr: null,
  traffic: '',
  spam_score: null,
  backlinks: null,
  link_type: 'Dofollow',
  base_price: 0,
  sale_price: null,
  content_service_price: 30.00,
  category_id: '',
  user_id: '',
  niches: [],
  niche_pricing: {},
  description: '',
  meta_title: '',
  meta_description: '',
  is_indexable: true,
  schemas: [],
  status: 'active',
  featured: false,
  featured_image: '',
  featured_image_alt_text: '',
};

const toFormData = (src: Website): WebsiteFormData => ({
  name: src.name || '',
  slug: src.slug || '',
  domain: src.domain || '',
  da: src.da ?? null,
  dr: src.dr ?? null,
  traffic: src.traffic || '',
  spam_score: src.spam_score ?? null,
  backlinks: src.backlinks ?? null,
  link_type: src.link_type || 'Dofollow',
  base_price: typeof src.base_price === 'number' ? src.base_price : parseFloat(String(src.base_price)) || 0,
  sale_price: src.sale_price !== null && src.sale_price !== undefined ? parseFloat(String(src.sale_price)) : null,
  content_service_price: typeof src.content_service_price === 'number' ? src.content_service_price : parseFloat(String(src.content_service_price)) || 30.00,
  category_id: src.category_id || '',
  user_id: src.user_id || '',
  niches: Array.isArray(src.niches) ? src.niches : [],
  niche_pricing: typeof src.niche_pricing === 'object' ? src.niche_pricing : {},
  description: src.description || '',
  meta_title: src.meta_title || '',
  meta_description: src.meta_description || '',
  is_indexable: src.is_indexable ?? true,
  schemas: Array.isArray(src.schemas) ? src.schemas : [],
  status: src.status || 'active',
  featured: src.featured || false,
  featured_image: src.featured_image || '',
  featured_image_alt_text: src.featured_image_alt_text || '',
});

export default function WebsiteForm({ websiteId, initialData }: WebsiteFormProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [isLoadingData, setIsLoadingData] = useState(true);
  const [generalCategories, setGeneralCategories] = useState<Category[]>([]);
  const [specialCategories, setSpecialCategories] = useState<Category[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [formData, setFormData] = useState<WebsiteFormData>(
    initialData ? toFormData(initialData) : EMPTY_FORM
  );

  useEffect(() => {
    const loadData = async () => {
      try {
        const promises = [
          fetch('/api/backend/admin/categories/dropdown?type=GENERAL'),
          fetch('/api/backend/admin/categories/dropdown?type=SPECIAL'),
          fetch('/api/backend/admin/users/dropdown'),
        ];

        if (websiteId && !initialData) {
          promises.push(fetch(`/api/backend/admin/websites/${websiteId}`));
        }

        const results = await Promise.all(promises);

        if (results[0].ok) {
          const categoriesData = await results[0].json();
          setGeneralCategories(categoriesData.categories);
        }

        if (results[1].ok) {
          const specialData = await results[1].json();
          setSpecialCategories(specialData.categories);
        }

        if (results[2].ok) {
          const usersData = await results[2].json();
          setUsers(usersData.users || []);
        }

        if (websiteId && !initialData && results[3]) {
          if (results[3].ok) {
            const websiteData = await results[3].json();
            setFormData(toFormData(websiteData.website));
          }
        }
      } catch (error) {
        console.error('Failed to load form data:', error);
        toast.error('Failed to load form data');
      } finally {
        setIsLoadingData(false);
      }
    };

    loadData();
  }, [websiteId, initialData]);

  const categoryOptions: SelectOption[] = generalCategories.map((cat) => ({
    value: cat.id,
    label: cat.name,
  }));

  const userOptions: SelectOption[] = users.map((user) => ({
    value: user.id,
    label: user.display_name || `${user.first_name} ${user.last_name}`.trim() || user.email,
  }));

  const linkTypeOptions: SelectOption[] = [
    { value: 'Dofollow', label: 'Do-Follow' },
    { value: 'Nofollow', label: 'No-Follow' }
  ];

  const statusOptions: SelectOption[] = [
    { value: 'active', label: 'Active' },
    { value: 'inactive', label: 'Inactive' },
    { value: 'sold_out', label: 'Sold Out' }
  ];

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  ) => {
    const { name, value, type } = e.target;
    const checked = type === 'checkbox' ? (e.target as HTMLInputElement).checked : undefined;

    if (type === 'number') {
      setFormData((prev) => ({
        ...prev,
        [name]: value === '' ? null : parseFloat(value)
      }));
    } else if (name === 'name' && !websiteId) {
      setFormData((prev) => ({
        ...prev,
        name: value,
        slug: generateSlug(value)
      }));
    } else {
      setFormData((prev) => ({
        ...prev,
        [name]: checked !== undefined ? checked : value
      }));
    }
  };

  const handleNicheToggle = (categoryId: string, categoryType: 'GENERAL' | 'SPECIAL') => {
    setFormData((prev) => {
      const currentNiches = prev.niches;
      
      if (currentNiches.includes(categoryId)) {
        const newNiches = currentNiches.filter(id => id !== categoryId);
        const newPricing = { ...prev.niche_pricing };
        if (categoryType === 'SPECIAL') {
          delete newPricing[categoryId];
        }
        return {
          ...prev,
          niches: newNiches,
          niche_pricing: newPricing
        };
      } else {
        return {
          ...prev,
          niches: [...currentNiches, categoryId]
        };
      }
    });
  };

  const handleNichePriceChange = (categoryId: string, price: number | null) => {
    setFormData((prev) => {
      const newPricing = { ...prev.niche_pricing };
      if (price === null || price <= 0) {
        delete newPricing[categoryId];
      } else {
        newPricing[categoryId] = price;
      }
      return {
        ...prev,
        niche_pricing: newPricing
      };
    });
  };

  const validate = (): boolean => {
    if (!formData.name.trim()) { toast.error('Website name is required'); return false; }
    if (!formData.slug.trim()) { toast.error('Slug is required'); return false; }
    if (!formData.domain.trim()) { toast.error('Domain is required'); return false; }
    if (formData.base_price <= 0) { toast.error('Base price must be greater than 0'); return false; }
    
    if (formData.sale_price !== null && formData.sale_price < 0) {
      toast.error('Sale price must be greater than or equal to 0');
      return false;
    }
    
    if (formData.sale_price !== null && formData.sale_price > formData.base_price) {
      toast.error('Sale price cannot be greater than base price');
      return false;
    }

    const slugRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
    if (!slugRegex.test(formData.slug)) {
      toast.error('Slug must contain only lowercase letters, numbers, and hyphens');
      return false;
    }

    const domainRegex = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
    if (!domainRegex.test(formData.domain)) {
      toast.error('Please enter a valid domain');
      return false;
    }

    if (formData.da !== null && (formData.da < 0 || formData.da > 100)) {
      toast.error('DA must be between 0 and 100');
      return false;
    }

    if (formData.dr !== null && (formData.dr < 0 || formData.dr > 100)) {
      toast.error('DR must be between 0 and 100');
      return false;
    }

    if (formData.spam_score !== null && (formData.spam_score < 0 || formData.spam_score > 100)) {
      toast.error('Spam score must be between 0 and 100');
      return false;
    }

    if (formData.backlinks !== null && formData.backlinks < 0) {
      toast.error('Backlinks must be a positive number');
      return false;
    }

    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;

    setLoading(true);
    try {
      const url = websiteId
        ? `/api/backend/admin/websites/${websiteId}`
        : '/api/backend/admin/websites';

      const response = await fetch(url, {
        method: websiteId ? 'PUT' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...formData,
          category_id: formData.category_id || null,
          user_id: formData.user_id || null,
          sale_price: formData.sale_price || null,
          da: formData.da || null,
          dr: formData.dr || null,
          spam_score: formData.spam_score || null,
          backlinks: formData.backlinks || null,
          link_type: formData.link_type,
          niches: formData.niches,
          niche_pricing: formData.niche_pricing
        }),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(websiteId ? 'Website updated successfully' : 'Website created successfully');
        router.push('/admin/dashboard/websites');
        router.refresh();
      } else {
        toast.error(data.error || `Failed to ${websiteId ? 'update' : 'create'} website`);
      }
    } catch {
      toast.error(`Failed to ${websiteId ? 'update' : 'create'} website`);
    } finally {
      setLoading(false);
    }
  };

  const getCategoryName = (categoryId: string) => {
    const category = [...generalCategories, ...specialCategories].find(cat => cat.id === categoryId);
    return category ? category.name : categoryId;
  };

  const getCategoryType = (categoryId: string): 'GENERAL' | 'SPECIAL' => {
    const category = [...generalCategories, ...specialCategories].find(cat => cat.id === categoryId);
    return category ? category.category_type : 'GENERAL';
  };

  const isEditing = Boolean(websiteId);

  if (isLoadingData && !initialData) {
    return (
      <div className="max-w-6xl mx-auto">
        <div className="bg-var-surface rounded-2xl shadow-var-card border border-var-border overflow-hidden p-8">
          <div className="text-center">
            <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-var-primary mb-4"></div>
            <p className="text-var-text-muted">Loading form data...</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <FormCard
      title={isEditing ? 'Edit Website' : 'Create New Website'}
      description={
        isEditing
          ? 'Update website information and settings'
          : 'Add a new website to your portfolio'
      }
      backHref="/admin/dashboard/websites"
      backLabel="Back to Websites"
    >
      <form onSubmit={handleSubmit} className="space-y-8">
        <FormSection title="Basic Information">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <FormField
              id="name"
              name="name"
              label="Website Name"
              value={formData.name}
              onChange={handleInputChange}
              placeholder="Enter website name"
              required
            />
            <FormField
              id="slug"
              name="slug"
              label="Slug"
              value={formData.slug}
              onChange={handleInputChange}
              placeholder="website-slug"
              hint="URL-friendly version of the name (auto-generated)"
              required
            />
            <FormField
              id="domain"
              name="domain"
              label="Domain"
              value={formData.domain}
              onChange={handleInputChange}
              placeholder="example.com"
              hint="Full domain name (e.g., example.com)"
              required
            />
            <FormSelect
              id="category_id"
              name="category_id"
              label="Main Category"
              value={formData.category_id}
              onChange={handleInputChange}
              options={categoryOptions}
              placeholder="Select a main category"
              hint="Main category for this website (GENERAL type only)"
            />
            <FormSelect
              id="user_id"
              name="user_id"
              label="Website Owner"
              value={formData.user_id}
              onChange={handleInputChange}
              options={userOptions}
              placeholder="Select an owner"
              hint="User who owns/manages this website"
            />
          </div>
        </FormSection>

        <FormSection title="Website Metrics">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <FormField
              id="da"
              name="da"
              label="Domain Authority (DA)"
              type="number"
              value={formData.da === null ? '' : String(formData.da)}
              onChange={handleInputChange}
              placeholder="0-100"
              min={0}
              max={100}
            />
            <FormField
              id="dr"
              name="dr"
              label="Domain Rating (DR)"
              type="number"
              value={formData.dr === null ? '' : String(formData.dr)}
              onChange={handleInputChange}
              placeholder="0-100"
              min={0}
              max={100}
            />
            <FormField
              id="traffic"
              name="traffic"
              label="Traffic Estimate"
              value={formData.traffic}
              onChange={handleInputChange}
              placeholder="e.g., 5000-10000"
            />
            <FormField
              id="spam_score"
              name="spam_score"
              label="Spam Score"
              type="number"
              value={formData.spam_score === null ? '' : String(formData.spam_score)}
              onChange={handleInputChange}
              placeholder="0-100"
              min={0}
              max={100}
            />
            <FormField
              id="backlinks"
              name="backlinks"
              label="Number of Backlinks"
              type="number"
              value={formData.backlinks === null ? '' : String(formData.backlinks)}
              onChange={handleInputChange}
              placeholder="e.g., 150"
              min={0}
            />
            <FormSelect
              id="link_type"
              name="link_type"
              label="Link Type"
              value={formData.link_type}
              onChange={handleInputChange}
              options={linkTypeOptions}
              hint="Type of backlinks provided"
            />
          </div>
        </FormSection>

        <FormSection title="Pricing Information">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <FormField
              id="base_price"
              name="base_price"
              label="Base Price"
              type="number"
              value={String(formData.base_price)}
              onChange={handleInputChange}
              placeholder="0.00"
              min={0.01}
              step={0.01}
              required
            />
            <FormField
              id="sale_price"
              name="sale_price"
              label="Sale Price (Optional)"
              type="number"
              value={formData.sale_price === null ? '' : String(formData.sale_price)}
              onChange={handleInputChange}
              placeholder="0.00"
              min={0}
              step={0.01}
              hint="Discounted price (leave empty for no sale)"
            />
            <FormField
              id="content_service_price"
              name="content_service_price"
              label="Content Service Price"
              type="number"
              value={String(formData.content_service_price)}
              onChange={handleInputChange}
              placeholder="30.00"
              min={0}
              step={0.01}
              hint="Price per article"
            />
          </div>
        </FormSection>

        <FormSection
          title="GENERAL Type Categories (Niches)"
          description="Select GENERAL type categories that this website accepts as niches"
        >
          {generalCategories.length > 0 ? (
            <div className="border border-var-border rounded-xl overflow-hidden">
              <div className="bg-var-surface-hover px-4 py-3 border-b border-var-border">
                <div className="flex items-center justify-between">
                  <h4 className="text-sm font-medium text-var-text">
                    Available GENERAL Categories ({generalCategories.length})
                  </h4>
                  <div className="text-sm text-var-text-muted">
                    {formData.niches.filter(id => getCategoryType(id) === 'GENERAL').length} selected
                  </div>
                </div>
              </div>
              <div className="p-4">
                <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
                  {generalCategories.map((category) => (
                    <div key={category.id} className="flex items-center">
                      <input
                        type="checkbox"
                        id={`general-cat-${category.id}`}
                        checked={formData.niches.includes(category.id)}
                        onChange={() => handleNicheToggle(category.id, 'GENERAL')}
                        className="w-4 h-4 text-var-primary border-var-border rounded focus:ring-var-primary"
                      />
                      <label htmlFor={`general-cat-${category.id}`} className="ml-2 text-sm text-var-text">
                        {category.name}
                      </label>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          ) : (
            <div className="text-center py-8 border-2 border-dashed border-var-border rounded-xl">
              <svg className="w-12 h-12 mx-auto text-var-text-muted mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
              <p className="text-var-text-muted">No GENERAL type categories found</p>
              <p className="text-sm text-var-text-muted mt-1">
                Create GENERAL type categories in Categories section first
              </p>
            </div>
          )}
        </FormSection>

        <FormSection
          title="SPECIAL Type Categories (With Pricing)"
          description="Select SPECIAL type categories and set special pricing for them"
        >
          {specialCategories.length > 0 ? (
            <div className="border border-var-border rounded-xl overflow-hidden">
              <div className="bg-var-surface-hover px-4 py-3 border-b border-var-border">
                <div className="flex items-center justify-between">
                  <h4 className="text-sm font-medium text-var-text">
                    Available SPECIAL Categories ({specialCategories.length})
                  </h4>
                  <div className="text-sm text-var-text-muted">
                    {formData.niches.filter(id => getCategoryType(id) === 'SPECIAL').length} selected
                  </div>
                </div>
              </div>
              <div className="divide-y divide-var-border">
                {specialCategories.map((category) => (
                  <div key={category.id} className="px-4 py-3">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center">
                        <input
                          type="checkbox"
                          id={`special-cat-${category.id}`}
                          checked={formData.niches.includes(category.id)}
                          onChange={() => handleNicheToggle(category.id, 'SPECIAL')}
                          className="w-4 h-4 text-var-accent-purple border-var-border rounded focus:ring-var-primary"
                        />
                        <label htmlFor={`special-cat-${category.id}`} className="ml-3 block">
                          <div className="text-sm font-medium text-var-text">
                            {category.name}
                          </div>
                          <div className="flex items-center space-x-2 mt-1">
                            <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-var-info-bg text-var-info">
                              SPECIAL
                            </span>
                          </div>
                        </label>
                      </div>
                      
                      {formData.niches.includes(category.id) && (
                        <div className="w-48">
                          <div className="relative">
                            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                              <span className="text-var-text-muted">$</span>
                            </div>
                            <input
                              type="number"
                              value={formData.niche_pricing[category.id] || ''}
                              onChange={(e) => handleNichePriceChange(category.id, e.target.value === '' ? null : parseFloat(e.target.value))}
                              step="0.01"
                              min="0"
                              className="w-full pl-8 pr-3 py-2 border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text transition-colors duration-200 text-sm"
                              placeholder="Special price"
                            />
                          </div>
                          <p className="text-xs text-var-text-muted mt-1">
                            {formData.niche_pricing[category.id] 
                              ? `Special price: $${formData.niche_pricing[category.id].toFixed(2)}`
                              : 'No special price set (will use base price)'
                            }
                          </p>
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ) : (
            <div className="text-center py-8 border-2 border-dashed border-var-border rounded-xl">
              <svg className="w-12 h-12 mx-auto text-var-text-muted mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
              <p className="text-var-text-muted">No SPECIAL type categories found</p>
              <p className="text-sm text-var-text-muted mt-1">
                Create SPECIAL type categories in Categories section first
              </p>
            </div>
          )}
        </FormSection>

        {formData.niches.length > 0 && (
          <div>
            <h4 className="text-sm font-medium text-var-text mb-2">Selected Niches:</h4>
            <div className="flex flex-wrap gap-2">
              {formData.niches.map((categoryId) => {
                const categoryType = getCategoryType(categoryId);
                const hasSpecialPrice = categoryType === 'SPECIAL' && formData.niche_pricing[categoryId];
                
                return (
                  <span
                    key={categoryId}
                    className={`inline-flex items-center px-3 py-1.5 rounded-full text-sm font-medium ${
                      categoryType === 'SPECIAL'
                        ? 'bg-var-info-bg text-var-info border border-var-info-border'
                        : 'bg-var-primary-muted text-var-primary border border-var-border'
                    }`}
                  >
                    {getCategoryName(categoryId)}
                    {categoryType === 'SPECIAL' && hasSpecialPrice && (
                      <span className="ml-1 font-bold">
                        (${formData.niche_pricing[categoryId].toFixed(2)})
                      </span>
                    )}
                    <button
                      type="button"
                      onClick={() => handleNicheToggle(categoryId, categoryType)}
                      className="ml-2 text-var-text-muted hover:text-var-text"
                    >
                      <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                      </svg>
                    </button>
                  </span>
                );
              })}
            </div>
          </div>
        )}

        <FormSection title="Featured Image">
          <div className="space-y-4">
            <ImageUpload
              value={formData.featured_image}
              onChange={(url) => setFormData((prev) => ({ ...prev, featured_image: url }))}
              uploadType="website"
              label="Upload Featured Image"
            />
            <FormField
              id="featured_image_alt_text"
              name="featured_image_alt_text"
              label="Alt Text"
              value={formData.featured_image_alt_text}
              onChange={handleInputChange}
              placeholder="Describe the image for accessibility and SEO"
              hint="Alternative text for the featured image (improves accessibility and SEO)"
            />
          </div>
        </FormSection>

        <FormSection title="Description">
          <div className="border border-var-border rounded-xl overflow-hidden">
            <RichTextEditor
              content={formData.description}
              onChange={(content) => setFormData((prev) => ({ ...prev, description: content }))}
            />
          </div>
        </FormSection>

        <FormSection title="SEO Settings">
          <div className="space-y-6">
            <FormField
              id="meta_title"
              name="meta_title"
              label="Meta Title"
              value={formData.meta_title}
              onChange={handleInputChange}
              placeholder="Enter meta title for SEO"
              hint="Recommended: 50–60 characters"
              maxLength={60}
              showCharCount
            />
            <FormField
              id="meta_description"
              name="meta_description"
              label="Meta Description"
              value={formData.meta_description}
              onChange={handleInputChange}
              type="textarea"
              placeholder="Enter meta description for SEO"
              hint="Recommended: 150–160 characters"
              maxLength={160}
              showCharCount
              rows={3}
            />
          </div>
        </FormSection>

        <FormSection
          title="JSON Schemas"
          description="Add structured data schemas for enhanced SEO"
        >
          <JsonSchemaManager
            schemas={formData.schemas}
            onChange={(schemas) => setFormData((prev) => ({ ...prev, schemas }))}
          />
        </FormSection>

        <FormSection title="Settings">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <FormSelect
              id="status"
              name="status"
              label="Website Status"
              value={formData.status}
              onChange={handleInputChange}
              options={statusOptions}
              hint="Control website visibility and availability"
            />
            <div className="flex items-center justify-between p-4 border border-var-border rounded-xl bg-var-surface-hover">
              <div>
                <h4 className="font-medium text-var-text">Featured Website</h4>
                <p className="text-sm text-var-text-muted mt-1">
                  Highlight this website as featured
                </p>
              </div>
              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="featured"
                  name="featured"
                  checked={formData.featured}
                  onChange={handleInputChange}
                  className="w-4 h-4 text-var-primary border-var-border rounded focus:ring-var-primary"
                />
                <label htmlFor="featured" className="ml-3 block text-sm font-medium text-var-text">
                  Featured
                </label>
              </div>
            </div>
            <div className="flex items-center justify-between p-4 border border-var-border rounded-xl bg-var-surface-hover md:col-span-2">
              <div>
                <h4 className="font-medium text-var-text">Indexable by Search Engines</h4>
                <p className="text-sm text-var-text-muted mt-1">
                  Allow search engines to index this website
                </p>
              </div>
              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="is_indexable"
                  name="is_indexable"
                  checked={formData.is_indexable}
                  onChange={handleInputChange}
                  className="w-4 h-4 text-var-primary border-var-border rounded focus:ring-var-primary"
                />
                <label htmlFor="is_indexable" className="ml-3 block text-sm font-medium text-var-text">
                  {formData.is_indexable ? 'Indexable' : 'No Index'}
                </label>
              </div>
            </div>
          </div>
        </FormSection>

        <FormActions
          cancelHref="/admin/dashboard/websites"
          submitLabel={isEditing ? 'Update Website' : 'Create Website'}
          loadingLabel={isEditing ? 'Updating...' : 'Creating...'}
          loading={loading}
        />
      </form>
    </FormCard>
  );
}