'use client';

import { useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import { getApiErrorMessage } from '@/lib/utils/apiError';
import { isReservedPath, normalizeSitePath } from '@/lib/validations/seo-path.validation';

interface SitemapUrlData {
  id?: string;
  url_path: string;
  priority: number;
  last_modified: string | null; // YYYY-MM-DD
  is_active: boolean;
}

interface SitemapUrlFormProps {
  mode: 'create' | 'edit';
  initialData?: SitemapUrlData | null;
}

type FieldErrors = Partial<Record<keyof SitemapUrlData, string>>;

const INPUT_STYLE = {
  background: 'var(--color-surface-alt)',
  border: '1px solid var(--color-border)',
  color: 'var(--color-text)',
} as const;

const LABEL_STYLE = { color: 'var(--color-text-secondary)' } as const;
const ERROR_STYLE = { color: 'var(--color-danger)' } as const;
const HINT_STYLE = { color: 'var(--color-text-tertiary)' } as const;

const EMPTY_ENTRY: SitemapUrlData = {
  url_path: '',
  priority: 0.5,
  last_modified: null,
  is_active: true,
};

// 0.0 – 1.0 in steps of 0.1.
const PRIORITIES = Array.from({ length: 11 }, (_, i) => i / 10);

function priorityHint(p: number): string {
  if (p >= 0.9) return 'Top page (home, main categories)';
  if (p >= 0.7) return 'Important page';
  if (p >= 0.4) return 'Normal page';
  return 'Minor page';
}

// Today's date as YYYY-MM-DD in the admin's local time.
function todayLocal(): string {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

// The API returns Zod failures as `errors: err.message` (a JSON string of
// issues) and its own conflicts as a plain { field: message } object.
function parseFieldErrors(errors: unknown): FieldErrors {
  if (errors && typeof errors === 'object' && !Array.isArray(errors)) return errors as FieldErrors;
  if (typeof errors === 'string') {
    try {
      const issues = JSON.parse(errors) as { path: (string | number)[]; message: string }[];
      const result: FieldErrors = {};
      for (const issue of issues) {
        const key = String(issue.path[0]) as keyof SitemapUrlData;
        if (!result[key]) result[key] = issue.message;
      }
      return result;
    } catch {
      return {};
    }
  }
  return {};
}

// Same rules as sitemap-url.validation.ts, so most mistakes show before saving.
function validate(data: SitemapUrlData): FieldErrors {
  const errs: FieldErrors = {};
  const path = normalizeSitePath(data.url_path);
  if (!path) errs.url_path = 'URL path is required';
  else if (!path.startsWith('/') || path.startsWith('//')) errs.url_path = 'URL path must start with / (a path on this site, e.g. /about)';
  else if (/\s/.test(path)) errs.url_path = 'URL path cannot contain spaces';
  else if (path.includes('#')) errs.url_path = 'URL path cannot contain #';
  else if (isReservedPath(path)) errs.url_path = 'URL path cannot be under /admin, /account, /api or /_next';
  else if (path.length > 255) errs.url_path = 'URL path must be at most 255 characters';
  return errs;
}

export default function SitemapUrlForm({ mode, initialData }: SitemapUrlFormProps) {
  const router = useRouter();
  const isEditing = mode === 'edit';

  const [formData, setFormData] = useState<SitemapUrlData>({ ...EMPTY_ENTRY, ...initialData });
  const [errors, setErrors] = useState<FieldErrors>({});
  const [loading, setLoading] = useState(false);

  const setField = useCallback(<K extends keyof SitemapUrlData>(key: K, value: SitemapUrlData[K]) => {
    setFormData((prev) => ({ ...prev, [key]: value }));
    setErrors((prev) => {
      if (!prev[key]) return prev;
      const next = { ...prev };
      delete next[key];
      return next;
    });
  }, []);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();

    const clientErrors = validate(formData);
    if (Object.keys(clientErrors).length > 0) {
      setErrors(clientErrors);
      toast.error('Please fix the highlighted fields');
      return;
    }

    setErrors({});
    setLoading(true);
    try {
      const payload = {
        url_path: formData.url_path,
        priority: formData.priority,
        last_modified: formData.last_modified || null,
        is_active: formData.is_active,
      };

      const res = await fetch(isEditing ? `/api/sitemap-urls/${initialData?.id}` : '/api/sitemap-urls', {
        method: isEditing ? 'PUT' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      const data = await res.json();

      if (!res.ok || !data.success) {
        const fieldErrors = parseFieldErrors(data.errors);
        setErrors(fieldErrors);
        toast.error(Object.keys(fieldErrors).length > 0 && res.status === 400
          ? 'Please fix the highlighted fields'
          : getApiErrorMessage(data, 'Failed to save sitemap URL'));
        return;
      }

      toast.success(data.message || (isEditing ? 'Sitemap URL updated successfully' : 'Sitemap URL created successfully'));
      router.push('/admin/dashboard/sitemap-urls');
      router.refresh();
    } catch (err) {
      console.error('[SitemapUrlForm]', err);
      toast.error('Network error — please try again');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="p-6 md:p-8" style={{
      background: 'var(--color-surface)',
      border: '1px solid var(--color-border)',
      borderRadius: 'var(--radius-card)',
      boxShadow: 'var(--shadow-card-md)',
      maxWidth: '1000px',
      width: '100%',
    }}>
      <form onSubmit={handleSubmit} noValidate>
        <div className="space-y-6">

          {/* Path */}
          <div>
            <label htmlFor="sitemap-path" className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
              URL Path <span className="text-red-500">*</span>
            </label>
            <input
              id="sitemap-path"
              type="text"
              value={formData.url_path}
              onChange={(e) => setField('url_path', e.target.value)}
              maxLength={255}
              placeholder="/about"
              autoComplete="off"
              spellCheck={false}
              className="w-full px-4 py-2.5 rounded-lg text-sm font-mono outline-none transition-all focus:ring-2 focus:ring-cta/20"
              style={{ ...INPUT_STYLE, border: errors.url_path ? '1px solid var(--color-danger)' : INPUT_STYLE.border }}
            />
            {errors.url_path
              ? <p className="text-xs mt-1" style={ERROR_STYLE}>{errors.url_path}</p>
              : <p className="text-xs mt-1" style={HINT_STYLE}>
                  A page on this site to list in the sitemap, e.g. /about or /offers. Use it for pages the sitemap doesn&apos;t already include on its own.
                </p>}
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Priority */}
            <div>
              <label htmlFor="sitemap-priority" className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Priority
              </label>
              <select
                id="sitemap-priority"
                value={formData.priority.toFixed(1)}
                onChange={(e) => setField('priority', Number(e.target.value))}
                className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                style={{ ...INPUT_STYLE, border: errors.priority ? '1px solid var(--color-danger)' : INPUT_STYLE.border }}
              >
                {PRIORITIES.map((p) => (
                  <option key={p} value={p.toFixed(1)}>{p.toFixed(1)} — {priorityHint(p)}</option>
                ))}
              </select>
              {errors.priority
                ? <p className="text-xs mt-1" style={ERROR_STYLE}>{errors.priority}</p>
                : <p className="text-xs mt-1" style={HINT_STYLE}>How important this page is compared with the rest of the site. 0.5 is normal.</p>}
            </div>

            {/* Last modified */}
            <div>
              <label htmlFor="sitemap-lastmod" className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Last Modified
              </label>
              <div className="flex gap-2">
                <input
                  id="sitemap-lastmod"
                  type="date"
                  value={formData.last_modified ?? ''}
                  onChange={(e) => setField('last_modified', e.target.value || null)}
                  className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                  style={{ ...INPUT_STYLE, border: errors.last_modified ? '1px solid var(--color-danger)' : INPUT_STYLE.border }}
                />
                <button
                  type="button"
                  onClick={() => setField('last_modified', todayLocal())}
                  className="px-3 py-2 rounded-lg text-sm font-medium whitespace-nowrap transition-all hover:opacity-80"
                  style={{ background: 'var(--color-surface-alt)', color: 'var(--color-text)', border: '1px solid var(--color-border)' }}
                >
                  Today
                </button>
              </div>
              {errors.last_modified
                ? <p className="text-xs mt-1" style={ERROR_STYLE}>{errors.last_modified}</p>
                : <p className="text-xs mt-1" style={HINT_STYLE}>When the page content last changed. Leave empty if unsure.</p>}
            </div>
          </div>

          {/* Status */}
          <div>
            <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>Status</label>
            <button
              type="button"
              onClick={() => setField('is_active', !formData.is_active)}
              className="px-4 py-2 rounded-lg text-sm font-medium transition-all"
              style={{
                background: formData.is_active ? 'var(--color-success)' : 'var(--color-surface-alt)',
                border: formData.is_active ? 'none' : '1px solid var(--color-border)',
                color: formData.is_active ? 'white' : 'var(--color-text-secondary)',
              }}
            >
              {formData.is_active ? '✅ Active' : '❌ Inactive'}
            </button>
            <p className="text-xs mt-1" style={HINT_STYLE}>
              Inactive entries are kept here but left out of the sitemap.
            </p>
          </div>

          {/* Actions */}
          <div className="flex gap-3 pt-4 border-t" style={{ borderColor: 'var(--color-border)' }}>
            <button
              type="submit"
              disabled={loading}
              className="px-6 py-2.5 rounded-lg text-sm font-medium transition-all disabled:opacity-50 hover:opacity-90"
              style={{ background: 'var(--color-cta)', color: 'white' }}
            >
              {loading ? (
                <span className="flex items-center gap-2">
                  <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none"/>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/>
                  </svg>
                  Saving...
                </span>
              ) : (isEditing ? 'Update Sitemap URL' : 'Create Sitemap URL')}
            </button>
            <button
              type="button"
              onClick={() => router.back()}
              className="px-6 py-2.5 rounded-lg text-sm font-medium transition-all hover:opacity-80"
              style={{
                background: 'var(--color-surface-alt)',
                color: 'var(--color-text)',
                border: '1px solid var(--color-border)',
              }}
            >
              Cancel
            </button>
          </div>
        </div>
      </form>
    </div>
  );
}
