'use client';

import { useEffect, useState, useRef } from 'react';
import dealerApi from '@/lib/dealer-axios';
import api from '@/lib/axios';

interface OutletRow { id: number; customer_code_bmu: string; outlet_name: string; city?: string; province?: string; contact_person?: string; email?: string; address?: string; is_active: boolean; }
interface CityOption { city_name: string; province_name: string; }

const EMPTY_ADD = { outlet_code: '', outlet_name: '', address: '', city: '', province: '', contact_person: '', email: '' };

export default function DealerOutletsPage() {
  const [outlets, setOutlets]     = useState<OutletRow[]>([]);
  const [loading, setLoading]     = useState(true);
  const [showAdd, setShowAdd]     = useState(false);
  const [addForm, setAddForm]     = useState(EMPTY_ADD);
  const [saving, setSaving]       = useState(false);
  const [msg, setMsg]             = useState('');

  // Edit state
  const [editOutlet, setEditOutlet] = useState<OutletRow | null>(null);
  const [editForm, setEditForm]     = useState({ outlet_name: '', address: '', city: '', province: '', contact_person: '', email: '' });
  const [editSaving, setEditSaving] = useState(false);
  const [editMsg, setEditMsg]       = useState('');

  // City lookup
  const [cityQuery, setCityQuery]           = useState('');
  const [citySuggestions, setCitySuggestions] = useState<CityOption[]>([]);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [editCityQuery, setEditCityQuery]   = useState('');
  const [editCitySugg, setEditCitySugg]     = useState<CityOption[]>([]);
  const [showEditSugg, setShowEditSugg]     = useState(false);
  const cityTimer = useRef<ReturnType<typeof setTimeout>>();
  const editCityTimer = useRef<ReturnType<typeof setTimeout>>();

  const load = () => {
    setLoading(true);
    dealerApi.get('/dealer/outlets').then(r => setOutlets(r.data.data ?? [])).catch(() => {}).finally(() => setLoading(false));
  };

  useEffect(() => { load(); }, []);

  // City lookup helpers
  const lookupCity = async (q: string, setSugg: (s: CityOption[]) => void, setShow: (b: boolean) => void) => {
    if (q.length < 2) { setSugg([]); setShow(false); return; }
    try {
      const res = await api.get(`/cities?q=${encodeURIComponent(q)}`);
      setSugg(res.data); setShow(true);
    } catch {}
  };

  const handleAddCityInput = (val: string) => {
    setCityQuery(val);
    setAddForm(f => ({ ...f, city: val, province: '' }));
    clearTimeout(cityTimer.current);
    cityTimer.current = setTimeout(() => lookupCity(val, setCitySuggestions, setShowSuggestions), 300);
  };

  const selectAddCity = (c: CityOption) => {
    setAddForm(f => ({ ...f, city: c.city_name, province: c.province_name }));
    setCityQuery(c.city_name); setShowSuggestions(false);
  };

  const handleEditCityInput = (val: string) => {
    setEditCityQuery(val);
    setEditForm(f => ({ ...f, city: val, province: '' }));
    clearTimeout(editCityTimer.current);
    editCityTimer.current = setTimeout(() => lookupCity(val, setEditCitySugg, setShowEditSugg), 300);
  };

  const selectEditCity = (c: CityOption) => {
    setEditForm(f => ({ ...f, city: c.city_name, province: c.province_name }));
    setEditCityQuery(c.city_name); setShowEditSugg(false);
  };

  // Add outlet
  const handleAdd = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true); setMsg('');
    try {
      await dealerApi.post('/dealer/outlets', addForm);
      setMsg('Outlet berhasil ditambahkan.');
      setShowAdd(false); setAddForm(EMPTY_ADD); setCityQuery('');
      load();
    } catch (err: any) {
      setMsg(err.response?.data?.message ?? 'Gagal menambahkan outlet.');
    } finally { setSaving(false); }
  };

  // Open edit modal
  const openEdit = (o: OutletRow) => {
    setEditOutlet(o);
    setEditForm({ outlet_name: o.outlet_name, address: o.address ?? '', city: o.city ?? '', province: o.province ?? '', contact_person: o.contact_person ?? '', email: o.email ?? '' });
    setEditCityQuery(o.city ?? '');
    setEditMsg('');
  };

  // Save edit
  const handleEdit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editOutlet) return;
    setEditSaving(true); setEditMsg('');
    try {
      await dealerApi.put(`/dealer/outlets/${editOutlet.id}`, editForm);
      setEditMsg('Outlet berhasil diperbarui.');
      setEditOutlet(null);
      load();
    } catch (err: any) {
      setEditMsg(err.response?.data?.message ?? 'Gagal memperbarui outlet.');
    } finally { setEditSaving(false); }
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-xl font-bold text-gray-800">Master Outlet</h1>
        <button onClick={() => { setShowAdd(!showAdd); setMsg(''); }}
          className="bg-blue-700 text-white px-4 py-2 rounded-lg text-sm hover:bg-blue-800">
          {showAdd ? 'Batal' : '+ Tambah Outlet'}
        </button>
      </div>

      {msg && <div className={`text-sm rounded-lg px-4 py-3 mb-4 ${msg.includes('berhasil') ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'}`}>{msg}</div>}

      {/* Add Form */}
      {showAdd && (
        <form onSubmit={handleAdd} className="bg-white rounded-xl shadow-sm p-6 mb-6 space-y-4">
          <h2 className="font-semibold text-gray-800">Tambah Outlet Baru</h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            {[['outlet_code', 'Kode Outlet (BMU)', true], ['outlet_name', 'Nama Outlet', true], ['address', 'Alamat', false], ['contact_person', 'Contact Person', false], ['email', 'Email', false]].map(([key, label, req]) => (
              <div key={key as string}>
                <label className="block text-xs text-gray-500 mb-1">{label as string} {req && <span className="text-red-500">*</span>}</label>
                <input value={(addForm as any)[key as string]} onChange={e => setAddForm(f => ({ ...f, [key as string]: e.target.value }))}
                  className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" required={req as boolean} />
              </div>
            ))}
            <CityField label="Kota" query={cityQuery} suggestions={citySuggestions} showSugg={showSuggestions}
              onInput={handleAddCityInput} onSelect={selectAddCity} onBlur={() => setTimeout(() => setShowSuggestions(false), 200)}
              province={addForm.province} />
          </div>
          <button type="submit" disabled={saving} className="bg-blue-700 text-white px-5 py-2 rounded-lg text-sm hover:bg-blue-800 disabled:opacity-60">
            {saving ? 'Menyimpan...' : 'Simpan'}
          </button>
        </form>
      )}

      {/* Edit Modal */}
      {editOutlet && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4">
          <div className="bg-white rounded-2xl shadow-xl w-full max-w-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="font-bold text-gray-800">Edit Outlet</h2>
              <button onClick={() => setEditOutlet(null)} className="text-gray-400 hover:text-gray-600 text-xl">✕</button>
            </div>

            {/* Kode BMU readonly */}
            <div className="mb-4 p-3 bg-gray-50 rounded-lg">
              <p className="text-xs text-gray-400 mb-0.5">Kode BMU (tidak dapat diubah)</p>
              <p className="text-sm font-mono font-medium text-gray-700">{editOutlet.customer_code_bmu}</p>
            </div>

            {editMsg && <div className={`text-sm rounded-lg px-4 py-3 mb-4 ${editMsg.includes('berhasil') ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'}`}>{editMsg}</div>}

            <form onSubmit={handleEdit} className="space-y-3">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                {[['outlet_name', 'Nama Outlet', true], ['address', 'Alamat', false], ['contact_person', 'Contact Person', false], ['email', 'Email', false]].map(([key, label, req]) => (
                  <div key={key as string}>
                    <label className="block text-xs text-gray-500 mb-1">{label as string} {req && <span className="text-red-500">*</span>}</label>
                    <input value={(editForm as any)[key as string]} onChange={e => setEditForm(f => ({ ...f, [key as string]: e.target.value }))}
                      className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" required={req as boolean} />
                  </div>
                ))}
                <CityField label="Kota" query={editCityQuery} suggestions={editCitySugg} showSugg={showEditSugg}
                  onInput={handleEditCityInput} onSelect={selectEditCity} onBlur={() => setTimeout(() => setShowEditSugg(false), 200)}
                  province={editForm.province} />
              </div>
              <div className="flex gap-3 pt-2">
                <button type="submit" disabled={editSaving} className="bg-blue-700 text-white px-5 py-2 rounded-lg text-sm hover:bg-blue-800 disabled:opacity-60">
                  {editSaving ? 'Menyimpan...' : 'Simpan Perubahan'}
                </button>
                <button type="button" onClick={() => setEditOutlet(null)} className="bg-gray-100 text-gray-700 px-5 py-2 rounded-lg text-sm hover:bg-gray-200">
                  Batal
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Table */}
      {loading ? <div className="text-center py-12 text-gray-400">Memuat...</div> : (
        <div className="bg-white rounded-2xl shadow-sm overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-gray-50 border-b">
              <tr>{['Kode BMU', 'Nama Outlet', 'Kota', 'Provinsi', 'Contact', 'Status', ''].map(h =>
                <th key={h} className="px-4 py-3 text-left text-xs font-medium text-gray-500">{h}</th>)}
              </tr>
            </thead>
            <tbody>
              {outlets.length === 0
                ? <tr><td colSpan={7} className="px-4 py-8 text-center text-gray-400">Belum ada outlet.</td></tr>
                : outlets.map(o => (
                  <tr key={o.id} className="border-b last:border-0 hover:bg-gray-50">
                    <td className="px-4 py-3 font-mono text-xs text-gray-600">{o.customer_code_bmu}</td>
                    <td className="px-4 py-3 font-medium text-gray-800">{o.outlet_name}</td>
                    <td className="px-4 py-3 text-gray-600">{o.city ?? '-'}</td>
                    <td className="px-4 py-3 text-gray-600">{o.province ?? '-'}</td>
                    <td className="px-4 py-3 text-gray-600">{o.contact_person ?? '-'}</td>
                    <td className="px-4 py-3">
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${o.is_active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}>
                        {o.is_active ? 'Aktif' : 'Nonaktif'}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <button onClick={() => openEdit(o)} className="text-xs text-blue-600 hover:text-blue-800 font-medium">Edit</button>
                    </td>
                  </tr>
                ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

// City field component with autocomplete
function CityField({ label, query, suggestions, showSugg, onInput, onSelect, onBlur, province }: {
  label: string; query: string; suggestions: CityOption[]; showSugg: boolean;
  onInput: (v: string) => void; onSelect: (c: CityOption) => void; onBlur: () => void; province: string;
}) {
  return (
    <>
      <div className="relative">
        <label className="block text-xs text-gray-500 mb-1">{label}</label>
        <input value={query} onChange={e => onInput(e.target.value)} onBlur={onBlur}
          placeholder="Ketik nama kota..."
          className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
        {showSugg && suggestions.length > 0 && (
          <ul className="absolute z-50 w-full bg-white border rounded-lg shadow-lg mt-1 max-h-40 overflow-y-auto">
            {suggestions.map((c, i) => (
              <li key={i} onMouseDown={() => onSelect(c)} className="px-3 py-2 text-sm hover:bg-blue-50 cursor-pointer">
                {c.city_name} <span className="text-gray-400 text-xs">— {c.province_name}</span>
              </li>
            ))}
          </ul>
        )}
      </div>
      <div>
        <label className="block text-xs text-gray-500 mb-1">Provinsi (otomatis)</label>
        <input value={province} readOnly className="w-full border rounded-lg px-3 py-2 text-sm bg-gray-50 text-gray-500" />
      </div>
    </>
  );
}
