'use client';

import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import toast from 'react-hot-toast';
import outletApi from '@/lib/outlet-axios';
import { useOutletAuthStore } from '@/store/outlet-auth';

const profileSchema = z.object({
  outlet_name:    z.string().min(2, 'Nama minimal 2 karakter'),
  address:        z.string().optional(),
  contact_person: z.string().optional(),
  city:           z.string().optional(),
  province:       z.string().optional(),
});

const pwSchema = z.object({
  current_password:      z.string().min(1, 'Wajib diisi'),
  password:              z.string().min(6, 'Minimal 6 karakter'),
  password_confirmation: z.string(),
}).refine((d) => d.password === d.password_confirmation, {
  message: 'Konfirmasi password tidak cocok',
  path: ['password_confirmation'],
});

type ProfileForm = z.infer<typeof profileSchema>;
type PwForm      = z.infer<typeof pwSchema>;

export default function OutletProfilePage() {
  const { outlet, setAuth, token } = useOutletAuthStore();
  const [tab, setTab]     = useState<'profile' | 'password'>('profile');
  const [saving, setSaving] = useState(false);

  const profileForm = useForm<ProfileForm>({ resolver: zodResolver(profileSchema) });
  const pwForm      = useForm<PwForm>({ resolver: zodResolver(pwSchema) });

  useEffect(() => {
    if (outlet) {
      profileForm.reset({
        outlet_name:    outlet.outlet_name,
        address:        outlet.address        ?? '',
        contact_person: outlet.contact_person ?? '',
        city:           outlet.city           ?? '',
        province:       outlet.province       ?? '',
      });
    }
  }, [outlet]);

  const saveProfile = async (data: ProfileForm) => {
    setSaving(true);
    try {
      const res = await outletApi.put('/outlet/profile', data);
      setAuth(res.data.data, token!);
      toast.success('Profil berhasil diperbarui');
    } catch (err: any) {
      toast.error(err.response?.data?.message ?? 'Gagal menyimpan');
    } finally {
      setSaving(false);
    }
  };

  const changePassword = async (data: PwForm) => {
    setSaving(true);
    try {
      await outletApi.post('/outlet/change-password', data);
      toast.success('Password berhasil diubah');
      pwForm.reset();
    } catch (err: any) {
      toast.error(err.response?.data?.message ?? 'Gagal mengubah password');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div>
      <h1 className="text-xl font-bold text-gray-800 mb-6">Profil Outlet</h1>

      {/* Info card */}
      <div className="bg-blue-50 border border-blue-100 rounded-xl p-4 mb-6 flex items-center gap-4">
        <div className="text-3xl">🏪</div>
        <div>
          <p className="font-semibold text-gray-800">{outlet?.outlet_name}</p>
          <p className="text-sm text-gray-500">Kode BMU: <strong>{outlet?.customer_code_bmu}</strong></p>
          <p className="text-xs text-gray-400 mt-0.5">QR: {outlet?.qr_code}</p>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 bg-gray-100 rounded-xl p-1 mb-6 w-fit">
        {(['profile', 'password'] as const).map((t) => (
          <button key={t} onClick={() => setTab(t)}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition ${
              tab === t ? 'bg-white shadow-sm text-blue-700' : 'text-gray-500 hover:text-gray-700'
            }`}>
            {t === 'profile' ? 'Data Outlet' : 'Ubah Password'}
          </button>
        ))}
      </div>

      {tab === 'profile' && (
        <form onSubmit={profileForm.handleSubmit(saveProfile)}
          className="bg-white rounded-2xl shadow-sm p-6 space-y-4 max-w-lg">

          {([
            { field: 'outlet_name',    label: 'Nama Outlet',      type: 'text' },
            { field: 'contact_person', label: 'Kontak Person',    type: 'text' },
            { field: 'city',           label: 'Kota',             type: 'text' },
            { field: 'province',       label: 'Provinsi',         type: 'text' },
          ] as const).map(({ field, label, type }) => (
            <div key={field}>
              <label className="block text-sm font-medium text-gray-700 mb-1">{label}</label>
              <input {...profileForm.register(field)} type={type}
                className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
              {profileForm.formState.errors[field] && (
                <p className="text-red-500 text-xs mt-1">{profileForm.formState.errors[field]?.message}</p>
              )}
            </div>
          ))}

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Alamat</label>
            <textarea {...profileForm.register('address')} rows={3}
              className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
          </div>

          <button type="submit" disabled={saving}
            className="bg-blue-700 text-white px-5 py-2 rounded-lg text-sm font-medium hover:bg-blue-800 disabled:opacity-60">
            {saving ? 'Menyimpan...' : 'Simpan'}
          </button>
        </form>
      )}

      {tab === 'password' && (
        <form onSubmit={pwForm.handleSubmit(changePassword)}
          className="bg-white rounded-2xl shadow-sm p-6 space-y-4 max-w-lg">
          {([
            { field: 'current_password',      label: 'Password Saat Ini' },
            { field: 'password',              label: 'Password Baru' },
            { field: 'password_confirmation', label: 'Konfirmasi Password Baru' },
          ] as const).map(({ field, label }) => (
            <div key={field}>
              <label className="block text-sm font-medium text-gray-700 mb-1">{label}</label>
              <input {...pwForm.register(field)} type="password"
                className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
              {pwForm.formState.errors[field] && (
                <p className="text-red-500 text-xs mt-1">{pwForm.formState.errors[field]?.message}</p>
              )}
            </div>
          ))}
          <button type="submit" disabled={saving}
            className="bg-blue-700 text-white px-5 py-2 rounded-lg text-sm font-medium hover:bg-blue-800 disabled:opacity-60">
            {saving ? 'Menyimpan...' : 'Ubah Password'}
          </button>
        </form>
      )}
    </div>
  );
}
