'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 api from '@/lib/axios';
import { useAuthStore } from '@/store/auth';

const profileSchema = z.object({
  full_name: z.string().min(3, 'Nama minimal 3 karakter'),
  email: z.string().email('Email tidak valid').optional().or(z.literal('')),
  address: z.string().optional(),
  birth_date: 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 ProfilePage() {
  const { user, setAuth, token } = useAuthStore();
  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) });

  // Always fetch fresh profile data on mount to get latest total_points
  useEffect(() => {
    api.get('/end-user/profile').then((res) => {
      const fresh = res.data.data;
      if (token) setAuth(fresh, token);
      profileForm.reset({
        full_name: fresh.full_name,
        email: fresh.email ?? '',
        address: fresh.address ?? '',
        birth_date: fresh.birth_date ?? '',
      });
    }).catch(() => {
      if (user) {
        profileForm.reset({
          full_name: user.full_name,
          email: user.email ?? '',
          address: user.address ?? '',
          birth_date: user.birth_date ?? '',
        });
      }
    });
  }, []);

  const saveProfile = async (data: ProfileForm) => {
    setSaving(true);
    try {
      const res = await api.put('/end-user/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 api.post('/end-user/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 Saya</h1>

      {/* 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 Profil' : '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">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Nama Lengkap</label>
            <input {...profileForm.register('full_name')}
              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.full_name && (
              <p className="text-red-500 text-xs mt-1">{profileForm.formState.errors.full_name.message}</p>
            )}
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Nomor HP</label>
            <input value={user?.phone ?? ''} disabled
              className="w-full border rounded-lg px-3 py-2 text-sm bg-gray-50 text-gray-400" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
            <input {...profileForm.register('email')} type="email"
              className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Alamat</label>
            <textarea {...profileForm.register('address')} rows={2}
              className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Tanggal Lahir</label>
            <input {...profileForm.register('birth_date')} type="date"
              className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
          </div>
          <div className="pt-2 flex items-center gap-3">
            <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>
            <span className="text-sm text-gray-500">Total Poin: <strong>{user?.total_points ?? 0}</strong></span>
          </div>
        </form>
      )}

      {tab === 'password' && (
        <form onSubmit={pwForm.handleSubmit(changePassword)} className="bg-white rounded-2xl shadow-sm p-6 space-y-4 max-w-lg">
          {(['current_password', 'password', 'password_confirmation'] as const).map((field) => (
            <div key={field}>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {field === 'current_password' ? 'Password Saat Ini' : field === 'password' ? 'Password Baru' : 'Konfirmasi Password Baru'}
              </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>
  );
}
