'use client';

import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import toast from 'react-hot-toast';
import dealerApi from '@/lib/dealer-axios';
import { useDealerAuthStore } from '@/store/dealer-auth';

export default function DealerProfilePage() {
  const { dealer, setAuth, token } = useDealerAuthStore();
  const [tab, setTab] = useState<'profile' | 'password'>('profile');
  const [saving, setSaving] = useState(false);
  const profileForm = useForm({ defaultValues: { dealer_name: '', email: '', address: '', contact_person: '', city: '', province: '' } });

  useEffect(() => {
    dealerApi.get('/dealer/profile').then(r => {
      const d = r.data.data;
      if (token) setAuth(d, token);
      profileForm.reset({ dealer_name: d.dealer_name, email: d.email ?? '', address: d.address ?? '', contact_person: d.contact_person ?? '', city: d.city ?? '', province: d.province ?? '' });
    }).catch(() => {});
  }, []);

  const saveProfile = async (data: any) => {
    setSaving(true);
    try {
      const res = await dealerApi.put('/dealer/profile', data);
      if (token) setAuth(res.data.data, token);
      toast.success('Profil berhasil diperbarui');
    } catch { toast.error('Gagal menyimpan'); } finally { setSaving(false); }
  };

  return (
    <div>
      <h1 className="text-xl font-bold text-gray-800 mb-6">Profil Dealer</h1>
      <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">Kode BMU</label><input value={dealer?.customer_code_bmu ?? ''} disabled className="w-full border rounded-lg px-3 py-2 text-sm bg-gray-50 text-gray-400" /></div>
          {[['dealer_name', 'Nama Dealer'], ['email', 'Email'], ['address', 'Alamat'], ['contact_person', 'Contact Person'], ['city', 'Kota'], ['province', 'Provinsi']].map(([field, label]) => (
            <div key={field}><label className="block text-sm font-medium text-gray-700 mb-1">{label}</label>
              <input {...profileForm.register(field as any)} 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' && (
        <div className="bg-white rounded-2xl shadow-sm p-8 max-w-lg">
          <div className="flex flex-col items-center justify-center py-8 text-center">
            <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mb-4">
              <svg className="w-8 h-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
              </svg>
            </div>
            <h3 className="text-lg font-semibold text-gray-800 mb-2">Ubah Password</h3>
            <p className="text-gray-600 text-sm">
              Harap ubah password melalui BMU Portal
            </p>
          </div>
        </div>
      )}
    </div>
  );
}
