'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Download, Eye, Star, Trash2 } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import ActionButton from '@/components/ui/ActionButton';
import Modal from '@/components/ui/Modal';
import ConfirmDialog from '@/components/ui/ConfirmDialog';
import { loyaltyApi } from '@/lib/api';
import { formatDateTime } from '@/lib/utils';

const Field = ({ label, value, mono = false, truncate = false }: { label: string; value: string; mono?: boolean; truncate?: boolean }) => (
  <div className="bg-muted/40 rounded-lg p-3">
    <p className="text-xs text-muted-foreground mb-1">{label}</p>
    <p className={`text-sm font-semibold text-foreground${mono ? ' font-mono' : ''}${truncate ? ' truncate' : ''}`} title={value}>{value || '—'}</p>
  </div>
);

const SectionHeader = ({ title }: { title: string }) => (
  <h3 className="text-xs font-bold uppercase tracking-widest text-muted-foreground mb-3 flex items-center gap-2">
    <span className="w-4 h-px bg-muted-foreground/40 inline-block" />{title}
  </h3>
);

const TIER_COLORS: Record<string, string> = {
  BRONZE:   'bg-orange-100 dark:bg-orange-900/30 text-orange-700 dark:text-orange-400 border-orange-200 dark:border-orange-800',
  SILVER:   'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 border-gray-200 dark:border-gray-600',
  GOLD:     'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-400 border-yellow-200 dark:border-yellow-800',
  PLATINUM: 'bg-indigo-100 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-400 border-indigo-200 dark:border-indigo-800',
};

const TIER_GRAD: Record<string, string> = {
  BRONZE:   'from-orange-500 to-orange-600',
  SILVER:   'from-gray-500 to-gray-600',
  GOLD:     'from-yellow-500 to-yellow-600',
  PLATINUM: 'from-indigo-600 to-indigo-700',
};

export default function LoyaltyPage() {
  const [filters, setFilters] = useState({ search: '', tier: '' });
  const [selected, setSelected] = useState<any>(null);
  const [toDelete, setToDelete] = useState<any>(null);
  const [deleteError, setDeleteError] = useState('');
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ['loyalty', filters],
    queryFn: () => loyaltyApi.getAccounts(filters),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => loyaltyApi.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['loyalty'] });
      setToDelete(null);
      setDeleteError('');
    },
    onError: (err: any) => setDeleteError(err?.message || 'Failed to delete loyalty account'),
  });

  const columns = [
    { key: 'passenger', label: 'Passenger', render: (account: any) => (
      <div>
        <div className="font-medium">{account.passenger?.fullName || account.user?.fullName || 'N/A'}</div>
        <div className="text-xs text-muted-foreground">{account.passenger?.email || account.user?.email || ''}</div>
      </div>
    )},
    { key: 'tier', label: 'Tier', render: (account: any) => (
      <span className={`inline-flex items-center gap-1 text-xs font-bold px-2.5 py-0.5 rounded-full border ${TIER_COLORS[account.tier] || TIER_COLORS.BRONZE}`}>
        <Star className="w-3 h-3" />{account.tier}
      </span>
    )},
    { key: 'pointsBalance', label: 'Points', render: (account: any) => (account.pointsBalance ?? 0).toLocaleString() },
    { key: 'lifetimePoints', label: 'Lifetime Points', render: (account: any) => (account.lifetimePoints ?? 0).toLocaleString() },
  ];

  const actions = [
    { label: 'View Details', onClick: (a: any) => setSelected(a), variant: 'secondary' as const, icon: Eye },
    { label: 'Delete', onClick: (a: any) => { setDeleteError(''); setToDelete(a); }, variant: 'danger' as const, icon: Trash2 },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Loyalty Program</h1>
          <p className="text-muted-foreground">Manage loyalty accounts and rewards</p>
        </div>
        <ActionButton icon={Download} variant="secondary">Export</ActionButton>
      </div>

      <div className="card">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="label">Search</label>
            <input type="text" placeholder="Search..." className="input" value={filters.search} onChange={(e) => setFilters({ ...filters, search: e.target.value })} />
          </div>
          <div>
            <label className="label">Tier</label>
            <select className="input" value={filters.tier} onChange={(e) => setFilters({ ...filters, tier: e.target.value })}>
              <option value="">All Tiers</option>
              <option value="BRONZE">Bronze</option>
              <option value="SILVER">Silver</option>
              <option value="GOLD">Gold</option>
              <option value="PLATINUM">Platinum</option>
            </select>
          </div>
        </div>
      </div>

      <DataTable
        data={Array.isArray(data) ? data : (data?.items || [])}
        columns={columns}
        actions={actions}
        loading={isLoading}
        emptyMessage="No loyalty accounts found"
      />

      {/* Delete Confirm Dialog */}
      <ConfirmDialog
        isOpen={!!toDelete}
        onClose={() => { setToDelete(null); setDeleteError(''); }}
        onConfirm={() => deleteMutation.mutate(toDelete.id)}
        title="Delete Loyalty Account"
        message={`Are you sure you want to delete the loyalty account for ${toDelete?.passenger?.fullName || 'this passenger'}? This will permanently remove all points, ledger entries, and rewards.`}
        confirmText="Delete"
        isDanger
        isLoading={deleteMutation.isPending}
        error={deleteError}
      />

      {/* Loyalty Details Modal */}
      <Modal isOpen={!!selected} onClose={() => setSelected(null)} title="Loyalty Account Details" size="xl">
        {selected && (() => {
          const a = selected;
          const tier = a.tier || 'BRONZE';
          const tierColor = TIER_COLORS[tier] || TIER_COLORS.BRONZE;
          const grad = TIER_GRAD[tier] || 'from-gray-600 to-gray-700';
          const passengerName = a.passenger?.fullName || a.user?.fullName || 'N/A';
          return (
            <div>
              <div className={`-mx-6 -mt-4 mb-6 px-6 py-5 bg-gradient-to-r ${grad} rounded-t-lg`}>
                <div className="flex items-center gap-4">
                  <div className="w-14 h-14 rounded-full bg-white/20 flex items-center justify-center shrink-0">
                    <Star className="w-7 h-7 text-white" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-white text-xl font-bold truncate">{passengerName}</p>
                    <p className="text-white/70 text-sm">{a.passenger?.email || a.user?.email || ''}</p>
                  </div>
                  <div className="text-right shrink-0">
                    <span className={`inline-flex items-center gap-1 text-xs font-bold px-3 py-1 rounded-full border ${tierColor}`}>
                      <Star className="w-3 h-3" />{tier}
                    </span>
                  </div>
                </div>
                <div className="mt-4 grid grid-cols-3 gap-3">
                  {[
                    { label: 'Points Balance', value: (a.pointsBalance ?? 0).toLocaleString() },
                    { label: 'Lifetime Points', value: (a.lifetimePoints ?? 0).toLocaleString() },
                    { label: 'Points Redeemed', value: (a.pointsRedeemed ?? 0).toLocaleString() },
                  ].map(({ label, value }) => (
                    <div key={label} className="bg-white/10 rounded-lg px-3 py-2">
                      <p className="text-white/70 text-xs">{label}</p>
                      <p className="text-white text-sm font-bold">{value}</p>
                    </div>
                  ))}
                </div>
              </div>

              <div className="space-y-6">
                <section>
                  <SectionHeader title="Account Overview" />
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                    <Field label="Current Tier" value={tier} />
                    <Field label="Points Balance" value={(a.pointsBalance ?? 0).toLocaleString()} />
                    <Field label="Lifetime Points" value={(a.lifetimePoints ?? 0).toLocaleString()} />
                    <Field label="Points Redeemed" value={(a.pointsRedeemed ?? 0).toLocaleString()} />
                    <Field label="Points Expiring" value={a.pointsExpiring ? a.pointsExpiring.toLocaleString() : 'N/A'} />
                    <Field label="Expiry Date" value={a.expiryDate ? formatDateTime(a.expiryDate) : 'N/A'} />
                    <Field label="Tier Since" value={a.tierAchievedAt ? formatDateTime(a.tierAchievedAt) : 'N/A'} />
                    <Field label="Next Tier" value={a.nextTier || 'N/A'} />
                  </div>
                </section>

                <section>
                  <SectionHeader title="Passenger" />
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                    <Field label="Full Name" value={a.passenger?.fullName || a.user?.fullName} />
                    <Field label="Email" value={a.passenger?.email || a.user?.email} truncate />
                    <Field label="Phone" value={a.passenger?.phone || a.user?.phone} />
                    <Field label="Passenger ID" value={a.passengerId || a.passenger?.id} mono truncate />
                  </div>
                </section>

                <section>
                  <SectionHeader title="Timestamps & IDs" />
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                    <Field label="Account Created" value={formatDateTime(a.createdAt)} />
                    <Field label="Last Updated" value={formatDateTime(a.updatedAt)} />
                    <Field label="Account ID" value={a.id} mono truncate />
                  </div>
                </section>
              </div>

              <div className="flex justify-end gap-2 pt-6 mt-2 border-t border-muted">
                <ActionButton variant="secondary" onClick={() => setSelected(null)}>Close</ActionButton>
              </div>
            </div>
          );
        })()}
      </Modal>
    </div>
  );
}
