'use client';

import { useEffect, useState, useCallback } from 'react';
import { useForm } from 'react-hook-form';
import outletApi from '@/lib/outlet-axios';

interface TopDevice {
  device_name: string;
  total_claims: number;
  approved_claims: number;
  unit_terjual: number;
  claim_rate: number;
}

interface DashboardData {
  total_sold: number;
  total_claims: number;
  approved_claims: number;
  pending_claims: number;
  claim_rate: number;
  top_devices: TopDevice[];
  start_date: string;
  end_date: string;
}

interface FilterForm {
  start_date: string;
  end_date: string;
}

export default function OutletDashboardPage() {
  const [data, setData] = useState<DashboardData | null>(null);
  const [loading, setLoading] = useState(true);

  const today = new Date().toISOString().slice(0, 10);
  const firstOfMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().slice(0, 10);

  const { register, handleSubmit, getValues } = useForm<FilterForm>({
    defaultValues: { start_date: firstOfMonth, end_date: today },
  });

  const loadDashboard = useCallback((filters: FilterForm) => {
    setLoading(true);
    outletApi.get(`/outlet/dashboard?start_date=${filters.start_date}&end_date=${filters.end_date}`)
      .then((r) => setData(r.data.data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    loadDashboard(getValues());
  }, []);

  const onFilter = (data: FilterForm) => loadDashboard(data);

  if (loading) {
    return (
      <div className="space-y-4">
        {[1, 2, 3].map((i) => (
          <div key={i} className="bg-white rounded-xl p-6 animate-pulse">
            <div className="h-4 bg-gray-200 rounded w-1/3 mb-3" />
            <div className="h-8 bg-gray-200 rounded w-1/4" />
          </div>
        ))}
      </div>
    );
  }

  if (!data) return <p className="text-gray-400">Gagal memuat data.</p>;

  const stats = [
    {
      label: 'Total Unit Terjual',
      value: data.total_sold.toLocaleString('id-ID'),
      sub: 'Dari data principal (activation date)',
      color: 'bg-blue-600',
      icon: (
        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10" />
        </svg>
      ),
    },
    {
      label: 'Total Klaim',
      value: data.total_claims.toLocaleString('id-ID'),
      sub: `${data.approved_claims} disetujui · ${data.pending_claims} pending`,
      color: 'bg-indigo-600',
      icon: (
        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
        </svg>
      ),
    },
    {
      label: 'Claim Rate',
      value: `${data.claim_rate}%`,
      sub: `${data.approved_claims} klaim / ${data.total_sold} unit terjual`,
      color: 'bg-emerald-600',
      icon: (
        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
        </svg>
      ),
    },
  ];

  return (
    <div>
      <h1 className="text-xl font-bold text-gray-800 mb-5">Dashboard Outlet</h1>

      {/* Filter Tanggal */}
      <form onSubmit={handleSubmit(onFilter)}
        className="bg-white rounded-xl shadow-sm p-4 mb-6 flex flex-wrap gap-3 items-end">
        <div>
          <label className="block text-xs text-gray-500 mb-1">Dari Tanggal</label>
          <input {...register('start_date')} type="date"
            className="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-xs text-gray-500 mb-1">Sampai Tanggal</label>
          <input {...register('end_date')} type="date"
            className="border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
        </div>
        <button type="submit"
          className="bg-blue-700 text-white px-4 py-2 rounded-lg text-sm hover:bg-blue-800">
          Tampilkan
        </button>
      </form>

      {/* Summary Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-8">
        {stats.map((s) => (
          <div key={s.label} className={`${s.color} rounded-2xl p-5 text-white`}>
            <div className="flex items-start justify-between">
              <div>
                <p className="text-sm font-medium opacity-80">{s.label}</p>
                <p className="text-3xl font-bold mt-1">{s.value}</p>
                <p className="text-xs opacity-70 mt-1">{s.sub}</p>
              </div>
              <div className="opacity-80">{s.icon}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Top 10 Claim Device */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
        <h2 className="text-base font-bold text-gray-800 mb-1">Top 10 Claim Device</h2>
        <p className="text-xs text-gray-400 mb-4">Perangkat dengan klaim terbanyak di outlet ini</p>

        {data.top_devices.length === 0 ? (
          <p className="text-gray-400 text-sm py-4 text-center">Belum ada data klaim.</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-gray-100 text-left text-gray-500 text-xs uppercase tracking-wide">
                  <th className="pb-3 font-semibold w-8">#</th>
                  <th className="pb-3 font-semibold">Perangkat</th>
                  <th className="pb-3 font-semibold text-right">Unit Terjual</th>
                  <th className="pb-3 font-semibold text-right">Total Klaim</th>
                  <th className="pb-3 font-semibold text-right">Disetujui</th>
                  <th className="pb-3 font-semibold text-right">Claim Rate</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {data.top_devices.map((d, i) => (
                  <tr key={i} className="hover:bg-gray-50 transition-colors">
                    <td className="py-3 text-gray-400 font-medium">{i + 1}</td>
                    <td className="py-3 font-semibold text-gray-800">{d.device_name}</td>
                    <td className="py-3 text-right text-blue-600 font-medium">{d.unit_terjual.toLocaleString('id-ID')}</td>
                    <td className="py-3 text-right text-gray-600">{d.total_claims.toLocaleString('id-ID')}</td>
                    <td className="py-3 text-right">
                      <span className="bg-green-100 text-green-700 px-2 py-0.5 rounded-full text-xs font-semibold">
                        {d.approved_claims.toLocaleString('id-ID')}
                      </span>
                    </td>
                    <td className="py-3 text-right">
                      <div className="flex items-center justify-end gap-2">
                        <div className="w-16 bg-gray-100 rounded-full h-1.5 hidden sm:block">
                          <div
                            className="bg-emerald-500 h-1.5 rounded-full"
                            style={{ width: `${Math.min(d.claim_rate, 100)}%` }}
                          />
                        </div>
                        <span className="text-xs font-semibold text-gray-700">{d.claim_rate}%</span>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
