'use client';

import { useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import { FaFacebookF, FaInstagram, FaLinkedinIn, FaGlobe } from 'react-icons/fa';
import { FaXTwitter } from 'react-icons/fa6';
import ImageUpload from '@/components/ui/ImageUpload';
import { getApiErrorMessage } from '@/lib/utils/apiError';

interface AuthorData {
  id?: string;
  full_name: string;
  slug: string;
  bio: string | null;
  profile_image: string | null;
  website: string | null;
  social_facebook: string | null;
  social_twitter: string | null;
  social_instagram: string | null;
  social_linkedin: string | null;
  status: boolean;
}

interface AuthorFormProps {
  mode: 'create' | 'edit';
  initialData?: AuthorData | null;
}

type FieldErrors = Partial<Record<keyof AuthorData, string>>;
type LinkField = 'website' | 'social_facebook' | 'social_twitter' | 'social_instagram' | 'social_linkedin';

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 BIO_MAX = 5000;

const LINK_FIELDS: { key: LinkField; label: string; placeholder: string; Icon: typeof FaGlobe }[] = [
  { key: 'website', label: 'Website', placeholder: 'https://example.com', Icon: FaGlobe },
  { key: 'social_facebook', label: 'Facebook', placeholder: 'https://facebook.com/username', Icon: FaFacebookF },
  { key: 'social_twitter', label: 'X / Twitter', placeholder: 'https://x.com/username', Icon: FaXTwitter },
  { key: 'social_instagram', label: 'Instagram', placeholder: 'https://instagram.com/username', Icon: FaInstagram },
  { key: 'social_linkedin', label: 'LinkedIn', placeholder: 'https://linkedin.com/in/username', Icon: FaLinkedinIn },
];

const EMPTY_AUTHOR: AuthorData = {
  full_name: '',
  slug: '',
  bio: null,
  profile_image: null,
  website: null,
  social_facebook: null,
  social_twitter: null,
  social_instagram: null,
  social_linkedin: null,
  status: true,
};

// Author slugs are lowercase ASCII (a-z, 0-9, hyphens) — see
// author.validation.ts. Accents are stripped; any other script is dropped,
// so a non-Latin name needs its slug typed by hand.
function toAuthorSlug(value: string): string {
  return value
    .normalize('NFKD')
    .replace(/[̀-ͯ]/g, '')
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .slice(0, 255);
}

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

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

  const [formData, setFormData] = useState<AuthorData>({ ...EMPTY_AUTHOR, ...initialData });
  // In create mode the slug follows the name until the user edits it.
  const [slugTouched, setSlugTouched] = useState(isEditing);
  const [errors, setErrors] = useState<FieldErrors>({});
  const [loading, setLoading] = useState(false);

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

  const handleNameChange = (value: string) => {
    setField('full_name', value);
    if (!slugTouched) setField('slug', toAuthorSlug(value));
  };

  const handleSlugChange = (value: string) => {
    setSlugTouched(true);
    // Keep typing natural: allow a trailing hyphen while editing.
    setField('slug', value.toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/-{2,}/g, '-'));
  };

  function clientValidate(): FieldErrors {
    const errs: FieldErrors = {};
    if (!formData.full_name.trim()) errs.full_name = 'Full name is required';
    const slug = formData.slug.replace(/^-+|-+$/g, '');
    if (!slug) errs.slug = 'Slug is required';
    else if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) errs.slug = 'Slug may only contain lowercase letters, numbers and hyphens';
    if ((formData.bio ?? '').length > BIO_MAX) errs.bio = `Bio must be at most ${BIO_MAX} characters`;
    for (const { key, label } of LINK_FIELDS) {
      const value = (formData[key] ?? '').trim();
      if (value && !/^https?:\/\/\S+\.\S+/i.test(value)) errs[key] = `${label} must be a full URL starting with https://`;
    }
    return errs;
  }

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

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

    setErrors({});
    setLoading(true);
    try {
      const payload = {
        ...formData,
        full_name: formData.full_name.trim(),
        slug: formData.slug.replace(/^-+|-+$/g, ''),
      };
      delete (payload as { id?: string }).id;

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

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

  const inputClass = (hasError: boolean) =>
    `w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${hasError ? 'border-red-500' : ''}`;

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

          {/* Photo + identity */}
          <div className="grid grid-cols-1 md:grid-cols-[220px_1fr] gap-6">
            <ImageUpload
              value={formData.profile_image}
              onUpload={(publicId) => setField('profile_image', publicId)}
              onRemove={() => setField('profile_image', null)}
              label="Profile Photo"
              folder="authors"
              maxSize={2}
              aspectRatio={1}
            />

            <div className="space-y-4">
              <div>
                <label htmlFor="author-name" className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                  Full Name <span className="text-red-500">*</span>
                </label>
                <input
                  id="author-name"
                  type="text"
                  value={formData.full_name}
                  onChange={(e) => handleNameChange(e.target.value)}
                  maxLength={100}
                  placeholder="e.g. Ayesha Khan"
                  className={inputClass(!!errors.full_name)}
                  style={INPUT_STYLE}
                />
                {errors.full_name && <p className="text-xs mt-1" style={ERROR_STYLE}>{errors.full_name}</p>}
              </div>

              <div>
                <label htmlFor="author-slug" className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                  Slug <span className="text-red-500">*</span>
                </label>
                <div className="flex items-center rounded-lg overflow-hidden" style={{
                  ...INPUT_STYLE,
                  border: errors.slug ? '1px solid var(--color-danger)' : INPUT_STYLE.border,
                }}>
                  <span className="pl-4 text-sm select-none shrink-0" style={HINT_STYLE}>/blogs/author/</span>
                  <input
                    id="author-slug"
                    type="text"
                    value={formData.slug}
                    onChange={(e) => handleSlugChange(e.target.value)}
                    maxLength={255}
                    placeholder="ayesha-khan"
                    className="w-full min-w-0 bg-transparent pr-4 py-2.5 text-sm outline-none"
                    style={{ color: 'var(--color-text)' }}
                  />
                </div>
                {errors.slug
                  ? <p className="text-xs mt-1" style={ERROR_STYLE}>{errors.slug}</p>
                  : <p className="text-xs mt-1" style={HINT_STYLE}>
                      Used in the author&apos;s public page URL. Lowercase English letters, numbers and hyphens.
                    </p>}
              </div>

              <div>
                <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>Status</label>
                <button
                  type="button"
                  onClick={() => setField('status', !formData.status)}
                  className="px-4 py-2 rounded-lg text-sm font-medium transition-all"
                  style={{
                    background: formData.status ? 'var(--color-success)' : 'var(--color-surface-alt)',
                    border: formData.status ? 'none' : '1px solid var(--color-border)',
                    color: formData.status ? 'white' : 'var(--color-text-secondary)',
                  }}
                >
                  {formData.status ? '✅ Active' : '❌ Inactive'}
                </button>
                <p className="text-xs mt-1" style={HINT_STYLE}>
                  Inactive authors are hidden on the blog (no byline, no author page).
                </p>
              </div>
            </div>
          </div>

          {/* Bio */}
          <div>
            <div className="flex justify-between items-baseline mb-1.5">
              <label htmlFor="author-bio" className="block text-sm font-medium" style={LABEL_STYLE}>Bio</label>
              <span className="text-xs" style={(formData.bio ?? '').length > BIO_MAX ? ERROR_STYLE : HINT_STYLE}>
                {(formData.bio ?? '').length}/{BIO_MAX}
              </span>
            </div>
            <textarea
              id="author-bio"
              rows={5}
              value={formData.bio ?? ''}
              onChange={(e) => setField('bio', e.target.value || null)}
              placeholder="A short introduction shown under the author's posts and on their author page."
              className={`${inputClass(!!errors.bio)} resize-y`}
              style={INPUT_STYLE}
            />
            {errors.bio && <p className="text-xs mt-1" style={ERROR_STYLE}>{errors.bio}</p>}
          </div>

          {/* Links */}
          <div>
            <h3 className="text-sm font-medium mb-3" style={LABEL_STYLE}>Website &amp; Social Profiles</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {LINK_FIELDS.map(({ key, label, placeholder, Icon }) => (
                <div key={key}>
                  <label htmlFor={`author-${key}`} className="block text-xs font-medium mb-1" style={HINT_STYLE}>
                    {label}
                  </label>
                  <div className="flex items-center rounded-lg overflow-hidden focus-within:ring-2 focus-within:ring-cta/20" style={{
                    ...INPUT_STYLE,
                    border: errors[key] ? '1px solid var(--color-danger)' : INPUT_STYLE.border,
                  }}>
                    <span className="pl-3 shrink-0" style={HINT_STYLE}><Icon size={14} /></span>
                    <input
                      id={`author-${key}`}
                      type="url"
                      inputMode="url"
                      value={formData[key] ?? ''}
                      onChange={(e) => setField(key, e.target.value || null)}
                      maxLength={500}
                      placeholder={placeholder}
                      className="w-full min-w-0 bg-transparent px-3 py-2.5 text-sm outline-none"
                      style={{ color: 'var(--color-text)' }}
                    />
                  </div>
                  {errors[key] && <p className="text-xs mt-1" style={ERROR_STYLE}>{errors[key]}</p>}
                </div>
              ))}
            </div>
          </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 Author' : 'Create Author')}
            </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>
  );
}
