// app/components/admin/pages/PageForm.tsx
'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';

// ── Shared form components ──────────────────────────────────────────────────
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 FormToggle from '@/app/components/admin/CommonComponents/Formtoggle';
import FormActions from '@/app/components/admin/CommonComponents/Formactions';
import JsonSchemaManager from '@/app/components/admin/CommonComponents/Jsonschemamanager';
// ───────────────────────────────────────────────────────────────────────────

// ── Types ──────────────────────────────────────────────────────────────────

interface PageFormData {
  page_title: string;
  page_slug: string;
  page_short_description: string;
  page_meta_title: string;
  page_meta_description: string;
  page_schemas: unknown[];
  is_indexable: boolean;
  is_active: boolean;
}

interface Page extends PageFormData {
  id: string;
  page_create_date: string;
  page_update_date: string;
}

interface PageFormProps {
  pageId?: string;
  initialData?: Page;
}

// ── Helpers ────────────────────────────────────────────────────────────────

const generateSlug = (title: string) =>
  title
    .toLowerCase()
    .replace(/[^\w\s]/gi, '')
    .replace(/\s+/g, '-')
    .trim();

const EMPTY_FORM: PageFormData = {
  page_title: '',
  page_slug: '',
  page_short_description: '',
  page_meta_title: '',
  page_meta_description: '',
  page_schemas: [],
  is_indexable: true,
  is_active: true,
};

const toFormData = (src: Page): PageFormData => ({
  page_title: src.page_title || '',
  page_slug: src.page_slug || '',
  page_short_description: src.page_short_description || '',
  page_meta_title: src.page_meta_title || '',
  page_meta_description: src.page_meta_description || '',
  page_schemas: Array.isArray(src.page_schemas) ? src.page_schemas : [],
  is_indexable: src.is_indexable ?? true,
  is_active: src.is_active ?? true,
});

// ── Component ──────────────────────────────────────────────────────────────

export default function PageForm({ pageId, initialData }: PageFormProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState<PageFormData>(
    initialData ? toFormData(initialData) : EMPTY_FORM
  );

  // ── Data fetching ──────────────────────────────────────────────────────

  useEffect(() => {
    if (pageId && !initialData) {
      const load = async () => {
        try {
          const res = await fetch(`/api/backend/admin/pages/${pageId}`);
          if (res.ok) {
            const data = await res.json();
            setFormData(toFormData(data.page));
          }
        } catch {
          toast.error('Failed to load form data');
        }
      };
      load();
    }
  }, [pageId, initialData]);

  // ── Handlers ──────────────────────────────────────────────────────────

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  ) => {
    const { name, value, type } = e.target;
    const checked = type === 'checkbox' ? (e.target as HTMLInputElement).checked : undefined;

    setFormData((prev) => ({
      ...prev,
      [name]: checked !== undefined ? checked : value,
      ...(name === 'page_title' && !pageId ? { page_slug: generateSlug(value) } : {}),
    }));
  };

  const validate = (): boolean => {
    if (!formData.page_title.trim()) { toast.error('Page title is required'); return false; }
    if (!formData.page_slug.trim()) { toast.error('Slug is required'); return false; }
    if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(formData.page_slug)) {
      toast.error('Slug must contain only lowercase letters, numbers, and hyphens');
      return false;
    }
    if (!formData.page_meta_title.trim()) { toast.error('Meta title is required'); return false; }
    if (!formData.page_meta_description.trim()) { toast.error('Meta description is required'); return false; }
    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;

    setLoading(true);
    try {
      const url = pageId ? `/api/backend/admin/pages/${pageId}` : '/api/backend/admin/pages';

      const response = await fetch(url, {
        method: pageId ? 'PUT' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(pageId ? 'Page updated successfully' : 'Page created successfully');
        router.push('/admin/dashboard/pages');
        router.refresh();
      } else {
        toast.error(data.error || `Failed to ${pageId ? 'update' : 'create'} page`);
      }
    } catch {
      toast.error(`Failed to ${pageId ? 'update' : 'create'} page`);
    } finally {
      setLoading(false);
    }
  };

  const isEditing = Boolean(pageId);

  return (
    <FormCard
      title={isEditing ? 'Edit Page' : 'Create New Page'}
      description={
        isEditing
          ? 'Update page information and settings'
          : 'Add a new page to your website'
      }
      backHref="/admin/dashboard/pages"
      backLabel="Back to Pages"
    >
      <form onSubmit={handleSubmit} className="space-y-8">

        {/* ── Basic Information ── */}
        <FormSection title="Basic Information">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <FormField
              id="page_title"
              name="page_title"
              label="Page Title"
              value={formData.page_title}
              onChange={handleInputChange}
              placeholder="Enter page title"
              required
            />

            <FormField
              id="page_slug"
              name="page_slug"
              label="Slug"
              value={formData.page_slug}
              onChange={handleInputChange}
              placeholder="page-slug"
              hint="URL-friendly version of the title (auto-generated)"
              required
            />

            <FormField
              id="page_short_description"
              name="page_short_description"
              label="Short Description"
              value={formData.page_short_description}
              onChange={handleInputChange}
              type="textarea"
              placeholder="Enter a brief summary of the page (optional)"
              hint="A brief summary of the page content. Maximum 300 characters."
              maxLength={300}
              showCharCount
              rows={3}
              className="md:col-span-2"
            />
          </div>
        </FormSection>

        {/* ── SEO Settings ── */}
        <FormSection title="SEO Settings">
          <div className="space-y-6">
            <FormField
              id="page_meta_title"
              name="page_meta_title"
              label="Meta Title"
              value={formData.page_meta_title}
              onChange={handleInputChange}
              placeholder="Enter meta title for SEO"
              hint="Recommended: 50–60 characters"
              maxLength={60}
              showCharCount
              required
            />

            <FormField
              id="page_meta_description"
              name="page_meta_description"
              label="Meta Description"
              value={formData.page_meta_description}
              onChange={handleInputChange}
              type="textarea"
              placeholder="Enter meta description for SEO"
              hint="Recommended: 150–160 characters"
              maxLength={160}
              showCharCount
              rows={3}
              required
            />
          </div>
        </FormSection>

        {/* ── JSON Schemas ── */}
        <FormSection
          title="JSON Schemas"
          description="Add structured data schemas for enhanced SEO"
        >
          <JsonSchemaManager
            schemas={formData.page_schemas}
            onChange={(schemas) => setFormData((prev) => ({ ...prev, page_schemas: schemas }))}
          />
        </FormSection>

        {/* ── Settings ── */}
        <FormSection title="Settings">
          <div className="space-y-4">
            <FormToggle
              id="is_active"
              name="is_active"
              label="Page Status"
              description="Active pages are visible on the website"
              checked={formData.is_active}
              onChange={handleInputChange}
              activeLabel="Active"
              inactiveLabel="Inactive"
            />

            <FormToggle
              id="is_indexable"
              name="is_indexable"
              label="Indexable by Search Engines"
              description="Allow search engines to index this page"
              checked={formData.is_indexable}
              onChange={handleInputChange}
              activeLabel="Indexable"
              inactiveLabel="No Index"
            />
          </div>
        </FormSection>

        {/* ── Actions ── */}
        <FormActions
          cancelHref="/admin/dashboard/pages"
          submitLabel={isEditing ? 'Update Page' : 'Create Page'}
          loadingLabel={isEditing ? 'Updating...' : 'Creating...'}
          loading={loading}
        />
      </form>
    </FormCard>
  );
}