'use client';

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

interface RedirectData {
  id?: string;
  source_path: string;
  destination_path: string;
  redirect_type: number;
  is_active: boolean;
}

interface RedirectFormProps {
  mode: 'create' | 'edit';
  initialData?: RedirectData | null;
}

type FieldErrors = Partial<Record<keyof RedirectData, 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_REDIRECT: RedirectData = {
  source_path: '',
  destination_path: '',
  redirect_type: 301,
  is_active: true,
};

const REDIRECT_TYPES: { value: number; title: string; hint: string }[] = [
  { value: 301, title: '301 · Permanent', hint: 'The page has moved for good. Search engines move its ranking to the new URL. Use this in most cases.' },
  { value: 302, title: '302 · Temporary', hint: 'The page is away for a while (a sale, maintenance). Search engines keep the old URL.' },
  { value: 307, title: '307 · Temporary (strict)', hint: 'Like 302, but browsers keep the request method (e.g. form posts).' },
  { value: 308, title: '308 · Permanent (strict)', hint: 'Like 301, but browsers keep the request method.' },
];

// 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 RedirectData;
        if (!result[key]) result[key] = issue.message;
      }
      return result;
    } catch {
      return {};
    }
  }
  return {};
}

// Same rules as redirect.validation.ts, so most mistakes show before saving.
function validate(data: RedirectData): FieldErrors {
  const errs: FieldErrors = {};
  const source = normalizeSitePath(data.source_path);
  const dest = data.destination_path.trim();

  if (!source) errs.source_path = 'Source path is required';
  else if (!source.startsWith('/') || source.startsWith('//')) errs.source_path = 'Source path must start with / (a path on this site, e.g. /old-page)';
  else if (/\s/.test(source)) errs.source_path = 'Source path cannot contain spaces';
  else if (/[?#]/.test(source)) errs.source_path = 'Source path cannot contain ? or #';
  else if (isReservedPath(source)) errs.source_path = 'Source path cannot be under /admin, /account, /api or /_next';

  if (!dest) errs.destination_path = 'Destination is required';
  else if (/\s/.test(dest)) errs.destination_path = 'Destination cannot contain spaces';
  else if (!((dest.startsWith('/') && !dest.startsWith('//')) || /^https?:\/\/[^/\s]+\.[^\s]+/i.test(dest))) {
    errs.destination_path = 'Use a path on this site (e.g. /new-page) or a full URL starting with https://';
  } else if (source && normalizeSitePath(dest) === source) {
    errs.destination_path = 'Destination must be different from the source path';
  }
  return errs;
}

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

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

  const setField = useCallback(<K extends keyof RedirectData>(key: K, value: RedirectData[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 = {
        source_path: formData.source_path,
        destination_path: formData.destination_path,
        redirect_type: formData.redirect_type,
        is_active: formData.is_active,
      };

      const res = await fetch(isEditing ? `/api/redirects/${initialData?.id}` : '/api/redirects', {
        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 redirect'));
        return;
      }

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

  const preview = formData.source_path.trim() && formData.destination_path.trim();

  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">

          {/* Paths */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label htmlFor="redirect-source" className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Source Path <span className="text-red-500">*</span>
              </label>
              <input
                id="redirect-source"
                type="text"
                value={formData.source_path}
                onChange={(e) => setField('source_path', e.target.value)}
                maxLength={500}
                placeholder="/old-page"
                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.source_path ? '1px solid var(--color-danger)' : INPUT_STYLE.border }}
              />
              {errors.source_path
                ? <p className="text-xs mt-1" style={ERROR_STYLE}>{errors.source_path}</p>
                : <p className="text-xs mt-1" style={HINT_STYLE}>The old address on this site that visitors or links still use.</p>}
            </div>

            <div>
              <label htmlFor="redirect-destination" className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Destination <span className="text-red-500">*</span>
              </label>
              <input
                id="redirect-destination"
                type="text"
                value={formData.destination_path}
                onChange={(e) => setField('destination_path', e.target.value)}
                maxLength={500}
                placeholder="/new-page or https://example.com/page"
                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.destination_path ? '1px solid var(--color-danger)' : INPUT_STYLE.border }}
              />
              {errors.destination_path
                ? <p className="text-xs mt-1" style={ERROR_STYLE}>{errors.destination_path}</p>
                : <p className="text-xs mt-1" style={HINT_STYLE}>Where visitors go instead: a path on this site or a full URL.</p>}
            </div>
          </div>

          {/* Type */}
          <div>
            <label className="block text-sm font-medium mb-2" style={LABEL_STYLE}>Redirect Type</label>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3" role="radiogroup" aria-label="Redirect type">
              {REDIRECT_TYPES.map((type) => {
                const selected = formData.redirect_type === type.value;
                return (
                  <button
                    key={type.value}
                    type="button"
                    role="radio"
                    aria-checked={selected}
                    onClick={() => setField('redirect_type', type.value)}
                    className="text-left p-3 rounded-lg transition-all"
                    style={{
                      background: selected ? 'var(--color-surface)' : 'var(--color-surface-alt)',
                      border: selected ? '2px solid var(--color-cta)' : '1px solid var(--color-border)',
                    }}
                  >
                    <div className="text-sm font-semibold" style={{ color: 'var(--color-text)' }}>{type.title}</div>
                    <div className="text-xs mt-0.5" style={HINT_STYLE}>{type.hint}</div>
                  </button>
                );
              })}
            </div>
            {errors.redirect_type && <p className="text-xs mt-1" style={ERROR_STYLE}>{errors.redirect_type}</p>}
          </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 redirects are kept here but don&apos;t send visitors anywhere.
            </p>
          </div>

          {/* Preview */}
          {preview && (
            <div className="flex flex-wrap items-center gap-2 px-4 py-3 rounded-lg text-sm" style={{
              background: 'var(--color-surface-alt)',
              border: '1px dashed var(--color-border)',
              color: 'var(--color-text-secondary)',
            }}>
              <span>Visitors to</span>
              <code className="font-mono break-all" style={{ color: 'var(--color-text)' }}>{normalizeSitePath(formData.source_path)}</code>
              <ArrowRight size={14} />
              <code className="font-mono break-all" style={{ color: 'var(--color-text)' }}>{formData.destination_path.trim()}</code>
              <span>({formData.redirect_type})</span>
            </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 Redirect' : 'Create Redirect')}
            </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>
  );
}
