// app/components/admin/authors/AuthorForm.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 ImageUpload     from '@/app/components/admin/CommonComponents/Imageupload';
import SocialLinkField from '@/app/components/admin/CommonComponents/Sociallinkfield';
// ───────────────────────────────────────────────────────────────────────────

// ── Types ─────────────────────────────────────────────────────────────────

interface AuthorFormData {
  full_name:        string;
  slug:             string;
  bio:              string;
  profile_image:    string;
  website:          string;
  social_facebook:  string;
  social_twitter:   string;
  social_instagram: string;
  social_linkedin:  string;
  status:           boolean;
}

interface Author extends AuthorFormData {
  id:         string;
  created_at: string;
  updated_at: string;
}

interface AuthorFormProps {
  authorId?:    string;
  initialData?: Author;
}

// ── Helpers ───────────────────────────────────────────────────────────────

const generateSlug = (name: string) =>
  name
    .toLowerCase()
    .replace(/[^\w\s]/gi, '')
    .replace(/\s+/g, '-')
    .trim();

const EMPTY_FORM: AuthorFormData = {
  full_name:        '',
  slug:             '',
  bio:              '',
  profile_image:    '',
  website:          '',
  social_facebook:  '',
  social_twitter:   '',
  social_instagram: '',
  social_linkedin:  '',
  status:           true,
};

const toFormData = (a: Author): AuthorFormData => ({
  full_name:        a.full_name        || '',
  slug:             a.slug             || '',
  bio:              a.bio              || '',
  profile_image:    a.profile_image    || '',
  website:          a.website          || '',
  social_facebook:  a.social_facebook  || '',
  social_twitter:   a.social_twitter   || '',
  social_instagram: a.social_instagram || '',
  social_linkedin:  a.social_linkedin  || '',
  status:           a.status           ?? true,
});

// ── Social field definitions ──────────────────────────────────────────────

const SOCIAL_FIELDS = [
  {
    name:        'social_facebook',
    label:       'Facebook',
    placeholder: 'https://facebook.com/username',
    icon: (
      <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
        <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z" />
      </svg>
    ),
  },
  {
    name:        'social_twitter',
    label:       'Twitter / X',
    placeholder: 'https://twitter.com/username',
    icon: (
      <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
        <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
      </svg>
    ),
  },
  {
    name:        'social_instagram',
    label:       'Instagram',
    placeholder: 'https://instagram.com/username',
    icon: (
      <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
        <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z" />
      </svg>
    ),
  },
  {
    name:        'social_linkedin',
    label:       'LinkedIn',
    placeholder: 'https://linkedin.com/in/username',
    icon: (
      <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
        <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z" />
      </svg>
    ),
  },
] as const;

// ── Component ─────────────────────────────────────────────────────────────

export default function AuthorForm({ authorId, initialData }: AuthorFormProps) {
  const router   = useRouter();
  const isEditing = Boolean(authorId);

  const [formData, setFormData] = useState<AuthorFormData>(
    initialData ? toFormData(initialData) : EMPTY_FORM
  );
  const [loading, setLoading] = useState(false);

  // ── Data fetching ─────────────────────────────────────────────────────

  useEffect(() => {
    if (authorId && !initialData) {
      fetch(`/api/backend/admin/authors/${authorId}`)
        .then(r => r.json())
        .then(data => setFormData(toFormData(data.author)))
        .catch(() => toast.error('Failed to load author data'));
    }
  }, [authorId, 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,
      // Auto-generate slug from name only when creating
      ...(name === 'full_name' && !authorId ? { slug: generateSlug(value) } : {}),
    }));
  };

  const validate = (): boolean => {
    if (!formData.full_name.trim()) { toast.error('Full name is required'); return false; }
    if (!formData.slug.trim())      { toast.error('Slug is required'); return false; }
    if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(formData.slug)) {
      toast.error('Slug must contain only lowercase letters, numbers, and hyphens');
      return false;
    }
    if (formData.website && !/^https?:\/\/.+/.test(formData.website)) {
      toast.error('Website must start with http:// or https://');
      return false;
    }
    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;

    setLoading(true);
    try {
      const url    = authorId ? `/api/backend/admin/authors/${authorId}` : '/api/backend/admin/authors';
      const method = authorId ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });
      const data = await response.json();

      if (response.ok) {
        toast.success(isEditing ? 'Author updated successfully' : 'Author created successfully');
        router.push('/admin/dashboard/authors');
        router.refresh();
      } else {
        toast.error(data.error || `Failed to ${isEditing ? 'update' : 'create'} author`);
      }
    } catch {
      toast.error(`Failed to ${isEditing ? 'update' : 'create'} author`);
    } finally {
      setLoading(false);
    }
  };

  // ── Render ────────────────────────────────────────────────────────────

  return (
    <FormCard
      title={isEditing ? 'Edit Author' : 'Create New Author'}
      description={
        isEditing
          ? 'Update author information and social links'
          : 'Add a new author profile to your platform'
      }
      backHref="/admin/dashboard/authors"
      backLabel="Back to Authors"
    >
      <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="full_name"
              name="full_name"
              label="Full Name"
              value={formData.full_name}
              onChange={handleInputChange}
              placeholder="Enter author's full name"
              required
            />

            <FormField
              id="slug"
              name="slug"
              label="Slug"
              value={formData.slug}
              onChange={handleInputChange}
              placeholder="author-slug"
              hint="URL-friendly version of the name (auto-generated)"
              required
            />

            <FormField
              id="website"
              name="website"
              label="Website"
              value={formData.website}
              onChange={handleInputChange}
              type="url"
              placeholder="https://example.com"
              className="md:col-span-2"
            />
          </div>
        </FormSection>

        {/* ── Profile Image ── */}
        <FormSection title="Profile Image">
          <ImageUpload
            value={formData.profile_image}
            onChange={url => setFormData(prev => ({ ...prev, profile_image: url }))}
            uploadType="author"
            label="Upload Profile Image"
            hint="JPG, PNG, or WebP. Max 5 MB. Recommended: 400×400 pixels."
            previewSize={96}
            previewShape="circle"
          />
        </FormSection>

        {/* ── Bio ── */}
        <FormField
          id="bio"
          name="bio"
          label="Author Bio"
          value={formData.bio}
          onChange={handleInputChange}
          type="textarea"
          placeholder="Write a short bio about the author..."
          hint={`${formData.bio.length} characters`}
          rows={5}
        />

        {/* ── Social Links ── */}
        <FormSection
          title="Social Links"
          description="Add the author's social media profile URLs"
        >
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {SOCIAL_FIELDS.map(field => (
              <SocialLinkField
                key={field.name}
                id={field.name}
                name={field.name}
                label={field.label}
                value={formData[field.name as keyof AuthorFormData] as string}
                onChange={handleInputChange}
                placeholder={field.placeholder}
                icon={field.icon}
              />
            ))}
          </div>
        </FormSection>

        {/* ── Settings ── */}
        <FormSection title="Settings">
          <FormToggle
            id="status"
            name="status"
            label="Author Status"
            description="Active authors are listed and attributed to content"
            checked={formData.status}
            onChange={handleInputChange}
            activeLabel="Active"
            inactiveLabel="Inactive"
          />
        </FormSection>

        {/* ── Actions ── */}
        <FormActions
          cancelHref="/admin/dashboard/authors"
          submitLabel={isEditing ? 'Update Author' : 'Create Author'}
          loadingLabel={isEditing ? 'Updating...' : 'Creating...'}
          loading={loading}
        />
      </form>
    </FormCard>
  );
}