// app/components/admin/redirects/RedirectForm.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 FormSelect      from '@/app/components/admin/CommonComponents/Formselect';
import FormToggle      from '@/app/components/admin/CommonComponents/Formtoggle';
import FormActions     from '@/app/components/admin/CommonComponents/Formactions';
// ───────────────────────────────────────────────────────────────────────────

// ── Types ─────────────────────────────────────────────────────────────────

interface RedirectData {
  id:               string;
  source_path:      string;
  destination_path: string;
  redirect_type:    301 | 302;
  is_active:        boolean;
  created_at:       string;
  updated_at:       string;
}

interface RedirectFormProps {
  redirectId?:   string;
  initialData?:  RedirectData;
}

interface FormData {
  source_path:      string;
  destination_path: string;
  redirect_type:    '301' | '302';
  is_active:        boolean;
}

// ── Constants ─────────────────────────────────────────────────────────────

const EMPTY_FORM: FormData = {
  source_path:      '',
  destination_path: '',
  redirect_type:    '301',
  is_active:        true,
};

const toFormData = (d: RedirectData): FormData => ({
  source_path:      d.source_path,
  destination_path: d.destination_path,
  redirect_type:    String(d.redirect_type) as '301' | '302',
  is_active:        d.is_active ?? true,
});

const REDIRECT_TYPE_OPTIONS = [
  { value: '301', label: '301 — Permanent' },
  { value: '302', label: '302 — Temporary' },
];

// ── Component ─────────────────────────────────────────────────────────────

export default function RedirectForm({ redirectId, initialData }: RedirectFormProps) {
  const router = useRouter();
  const isEdit = Boolean(redirectId);

  const [form,   setForm]   = useState<FormData>(EMPTY_FORM);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (initialData) {
      setForm(toFormData(initialData));
      return;
    }
    if (!redirectId) return;

    const load = async () => {
      try {
        const res  = await fetch(`/api/backend/admin/redirects/${redirectId}`);
        const data = await res.json();
        if (res.ok) {
          setForm(toFormData(data.redirect));
        } else {
          toast.error(data.error || 'Failed to load redirect');
        }
      } catch {
        toast.error('Failed to load redirect data');
      }
    };

    load();
  }, [redirectId, initialData]);

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  ) => {
    const { name, value, type } = e.target;
    const checked = type === 'checkbox' ? (e.target as HTMLInputElement).checked : undefined;
    setForm(prev => ({ ...prev, [name]: checked !== undefined ? checked : value }));
  };

  const validate = (): boolean => {
    if (!form.source_path.trim()) {
      toast.error('Source path is required');
      return false;
    }
    if (!form.destination_path.trim()) {
      toast.error('Destination path is required');
      return false;
    }
    if (form.source_path.trim() === form.destination_path.trim()) {
      toast.error('Source and destination paths cannot be the same');
      return false;
    }
    const src = form.source_path.trim();
    if (!src.startsWith('/') && !src.startsWith('http')) {
      toast.error('Source path must start with / or be a full URL');
      return false;
    }
    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;

    setSaving(true);
    try {
      const url    = isEdit
        ? `/api/backend/admin/redirects/${redirectId}`
        : '/api/backend/admin/redirects';
      const method = isEdit ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          source_path:      form.source_path.trim(),
          destination_path: form.destination_path.trim(),
          redirect_type:    Number(form.redirect_type),
          is_active:        form.is_active,
        }),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(isEdit ? 'Redirect updated successfully' : 'Redirect created successfully');
        router.push('/admin/dashboard/redirects');
        router.refresh();
      } else {
        toast.error(data.error || `Failed to ${isEdit ? 'update' : 'create'} redirect`);
      }
    } catch {
      toast.error(`Failed to ${isEdit ? 'update' : 'create'} redirect`);
    } finally {
      setSaving(false);
    }
  };

  return (
    <FormCard
      title={isEdit ? 'Edit Redirect' : 'Create New Redirect'}
      description={
        isEdit
          ? 'Update redirect rule information and settings'
          : 'Add a new URL redirect rule'
      }
      backHref="/admin/dashboard/redirects"
      backLabel="Back to Redirects"
    >
      <form onSubmit={handleSubmit} className="space-y-8">

        <FormSection title="Redirect Paths">
          <div className="space-y-6">

            <FormField
              id="source_path"
              name="source_path"
              label="Source Path"
              value={form.source_path}
              onChange={handleInputChange}
              placeholder="/old-page"
              disabled={isEdit}
              hint={
                isEdit
                  ? 'Source path cannot be changed after creation.'
                  : 'The URL path that will trigger this redirect (e.g. /old-page).'
              }
              required
            />

            <div className="flex items-center gap-3 py-1">
              <div className="flex-1 border-t border-dashed border-var-border" />
              <div className="flex items-center justify-center w-9 h-9 rounded-full bg-var-primary-muted border border-var-primary shrink-0">
                <svg className="w-4 h-4 text-var-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 13l-5 5m0 0l-5-5m5 5V6" />
                </svg>
              </div>
              <div className="flex-1 border-t border-dashed border-var-border" />
            </div>

            <FormField
              id="destination_path"
              name="destination_path"
              label="Destination Path"
              value={form.destination_path}
              onChange={handleInputChange}
              placeholder="/new-page or https://example.com/page"
              hint="Where to redirect to. Can be a relative path (e.g. /new-page) or a full URL."
              required
            />
          </div>
        </FormSection>

        {(form.source_path || form.destination_path) && (
          <div>
            <h3 className="text-lg font-medium text-var-text mb-4">Preview</h3>
            <div className="rounded-xl bg-var-surface-hover border border-var-border p-4">
              <div className="flex items-center gap-2 flex-wrap">
                <code className="text-sm font-mono text-var-text bg-var-surface border border-var-border px-2.5 py-1.5 rounded-lg">
                  {form.source_path || '…'}
                </code>
                <div className="flex items-center gap-1.5">
                  <svg className="w-4 h-4 text-var-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
                  </svg>
                  <span className={`text-xs font-semibold px-2 py-0.5 rounded-full border ${
                    form.redirect_type === '301'
                      ? 'bg-var-warning-bg text-var-warning-text border-var-warning-border'
                      : 'bg-var-info-bg text-var-info-text border-var-info-border'
                  }`}>
                    {form.redirect_type}
                  </span>
                  <svg className="w-4 h-4 text-var-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
                  </svg>
                </div>
                <code className="text-sm font-mono text-var-primary bg-var-primary-muted border border-var-primary px-2.5 py-1.5 rounded-lg">
                  {form.destination_path || '…'}
                </code>
              </div>
            </div>
          </div>
        )}

        <FormSection title="Settings">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">

            <FormSelect
              id="redirect_type"
              name="redirect_type"
              label="Redirect Type"
              value={form.redirect_type}
              onChange={handleInputChange}
              options={REDIRECT_TYPE_OPTIONS}
              hint={
                form.redirect_type === '301'
                  ? '301 passes SEO link equity to the destination URL.'
                  : '302 does not pass SEO value — use for temporary moves.'
              }
              required
            />

            <FormToggle
              id="is_active"
              name="is_active"
              label={form.is_active ? 'Active' : 'Inactive'}
              description={
                form.is_active
                  ? 'Redirect is live and will be applied'
                  : 'Redirect is disabled and will be ignored'
              }
              checked={form.is_active}
              onChange={handleInputChange}
              activeLabel="Active"
              inactiveLabel="Inactive"
            />

          </div>
        </FormSection>

        <FormActions
          cancelHref="/admin/dashboard/redirects"
          submitLabel={isEdit ? 'Update Redirect' : 'Create Redirect'}
          loadingLabel={isEdit ? 'Updating…' : 'Creating…'}
          loading={saving}
        />

      </form>
    </FormCard>
  );
}