'use client';

import { useFormState, useFormStatus } from 'react-dom';
import type { ApiVendorProfile } from '@/lib/backend-api';
import { updateVendorProfile, type VendorProfileFormState } from '@/app/vendor/profile/actions';
import { SOCIAL_KEYS, DAY_KEYS } from '@/lib/vendor-profile-fields';
import { vendorStorefrontRoute } from '@/lib/routes';

const initialState: VendorProfileFormState = undefined;

const SOCIAL_LABELS: Record<string, string> = {
  facebook: 'Facebook',
  instagram: 'Instagram',
  whatsapp: 'WhatsApp',
  tiktok: 'TikTok',
  youtube: 'YouTube',
  pinterest: 'Pinterest',
  twitter: 'Twitter',
  website: 'Website',
};

function SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <button type="submit" disabled={pending} className="btn-primary disabled:opacity-60">
      {pending ? 'Saving…' : 'Save Storefront Profile'}
    </button>
  );
}

export function VendorProfileForm({ profile }: { profile: ApiVendorProfile }) {
  const [state, formAction] = useFormState(updateVendorProfile, initialState);
  const errors = state?.errors ?? {};
  const socialLinks = profile.social_links ?? {};
  const businessHours = profile.business_hours ?? {};

  return (
    <form action={formAction} className="space-y-6" encType="multipart/form-data">
      {state?.success && (
        <div className="rounded-md border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-700">
          Storefront profile saved.
        </div>
      )}

      {Object.keys(errors).length > 0 && (
        <div className="rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
          <ul className="list-inside list-disc">
            {Object.values(errors).flat().map((error) => (
              <li key={error}>{error}</li>
            ))}
          </ul>
        </div>
      )}

      {profile.store_slug && (
        <p className="text-xs text-navy-500">
          Your storefront is live at{' '}
          <a
            href={vendorStorefrontRoute(profile.store_slug)}
            target="_blank"
            rel="noopener noreferrer"
            className="font-semibold text-gold-600 hover:text-gold-700"
          >
            {vendorStorefrontRoute(profile.store_slug)}
          </a>
        </p>
      )}

      <div className="grid gap-5 sm:grid-cols-2">
        <div>
          <label className="block text-sm font-semibold text-navy-800">Store Name</label>
          <input
            type="text"
            name="store_name"
            defaultValue={profile.store_name ?? ''}
            required
            className="mt-1.5 w-full rounded-md border-navy-100 text-sm focus:border-gold-500 focus:ring-gold-500"
          />
        </div>
        <div>
          <label className="block text-sm font-semibold text-navy-800">Store URL Slug</label>
          <input
            type="text"
            name="store_slug"
            defaultValue={profile.store_slug ?? ''}
            required
            pattern="[a-z0-9-]+"
            placeholder="my-craft-store"
            className="mt-1.5 w-full rounded-md border-navy-100 text-sm focus:border-gold-500 focus:ring-gold-500"
          />
        </div>
      </div>

      <div>
        <label className="block text-sm font-semibold text-navy-800">About Your Store</label>
        <textarea
          name="about_vendor"
          rows={4}
          defaultValue={profile.about_vendor ?? ''}
          className="mt-1.5 w-full rounded-md border-navy-100 text-sm focus:border-gold-500 focus:ring-gold-500"
        />
      </div>

      <div className="grid gap-5 sm:grid-cols-2">
        <div>
          <label className="block text-sm font-semibold text-navy-800">Business Address</label>
          <input
            type="text"
            name="business_address"
            defaultValue={profile.business_address ?? ''}
            className="mt-1.5 w-full rounded-md border-navy-100 text-sm focus:border-gold-500 focus:ring-gold-500"
          />
        </div>
        <div>
          <label className="block text-sm font-semibold text-navy-800">Store Logo</label>
          <input
            type="file"
            name="store_logo"
            accept="image/*"
            className="mt-1.5 w-full text-sm"
          />
          {profile.store_logo && <p className="mt-1 text-xs text-navy-400">Current logo is set — choose a file to replace it.</p>}
        </div>
        <div>
          <label className="block text-sm font-semibold text-navy-800">Contact Number</label>
          <input
            type="text"
            name="contact_number"
            defaultValue={profile.contact_number ?? ''}
            className="mt-1.5 w-full rounded-md border-navy-100 text-sm focus:border-gold-500 focus:ring-gold-500"
          />
        </div>
        <div>
          <label className="block text-sm font-semibold text-navy-800">WhatsApp Number</label>
          <input
            type="text"
            name="whatsapp_number"
            defaultValue={profile.whatsapp_number ?? ''}
            className="mt-1.5 w-full rounded-md border-navy-100 text-sm focus:border-gold-500 focus:ring-gold-500"
          />
        </div>
      </div>

      <div>
        <h3 className="text-sm font-semibold text-navy-800">Social Links</h3>
        <div className="mt-2 grid gap-3 sm:grid-cols-2">
          {SOCIAL_KEYS.map((key) => (
            <div key={key}>
              <label className="block text-xs font-medium text-navy-600">{SOCIAL_LABELS[key]}</label>
              <input
                type="text"
                name={`social_${key}`}
                defaultValue={socialLinks[key] ?? ''}
                placeholder="https://..."
                className="mt-1 w-full rounded-md border-navy-100 text-sm focus:border-gold-500 focus:ring-gold-500"
              />
            </div>
          ))}
        </div>
      </div>

      <div>
        <h3 className="text-sm font-semibold text-navy-800">Business Hours</h3>
        <div className="mt-2 grid gap-3 sm:grid-cols-2">
          {DAY_KEYS.map((day) => (
            <div key={day}>
              <label className="block text-xs font-medium capitalize text-navy-600">{day}</label>
              <input
                type="text"
                name={`hours_${day}`}
                defaultValue={businessHours[day] ?? ''}
                placeholder="9:00 AM - 5:00 PM"
                className="mt-1 w-full rounded-md border-navy-100 text-sm focus:border-gold-500 focus:ring-gold-500"
              />
            </div>
          ))}
        </div>
      </div>

      <SubmitButton />
    </form>
  );
}
