import { mdiCellphoneCog, mdiClipboardCheckOutline, mdiCreditCardOutline, mdiQrcodeScan, mdiWhatsapp } from '@mdi/js';
import axios from 'axios';
import Head from 'next/head';
import React, { ReactElement, useEffect, useMemo, useState } from 'react';
import BaseButton from '../components/BaseButton';
import CardBox from '../components/CardBox';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import LayoutAuthenticated from '../layouts/Authenticated';
import { getPageTitle } from '../config';
import { useAppSelector } from '../stores/hooks';

type IntakeForm = {
  fullName: string;
  contactPhone: string;
  deviceType: string;
  deviceBrand: string;
  deviceModel: string;
  deviceColor: string;
  accessoriesReceived: string;
  deviceCondition: string;
  problemDescription: string;
  paymentProvider: 'transfermovil' | 'enzona';
  depositAmount: string;
  acceptsMarketing: boolean;
  source: 'public_web' | 'qr';
};

type IntakeResult = {
  order: { id: string; order_number: string; status: string; requested_at: string };
  device: { brand: string; model: string };
  payment: { provider_label: string; reference_code: string; status: string; amount?: string; currency: string };
  whatsapp: { to_number: string; status: string; message_body: string };
};

type RecentOrder = {
  id: string;
  order_number: string;
  status: string;
  problem_description: string;
  createdAt: string;
  device?: { brand?: string; model?: string };
  payments_repair_order?: Array<{
    reference_code?: string;
    status?: string;
    payment_method?: { display_name?: string; provider?: string };
  }>;
  whatsapp_notifications_repair_order?: Array<{ status?: string; to_number?: string }>;
};

const statusLabels: Record<string, string> = {
  new: 'Nuevo',
  diagnosing: 'Diagnóstico',
  awaiting_approval: 'Esperando aprobación',
  approved: 'Aprobado',
  in_repair: 'En reparación',
  ready_for_pickup: 'Listo para recoger',
  delivered: 'Entregado',
  cancelled: 'Cancelado',
};

const paymentProviders = [
  {
    value: 'transfermovil',
    label: 'Transfermóvil',
    helper: 'Ideal para clientes en Cuba. El pedido queda pendiente hasta confirmar el comprobante.',
  },
  {
    value: 'enzona',
    label: 'Enzona',
    helper: 'Usa la referencia generada y envía el comprobante al equipo del taller.',
  },
] as const;

const fieldClass = 'w-full rounded-2xl border border-slate-200 bg-white/90 px-4 py-3 text-sm text-slate-900 shadow-sm outline-none transition focus:border-cyan-400 focus:ring-4 focus:ring-cyan-200/60 dark:border-dark-700 dark:bg-dark-900 dark:text-slate-100';
const labelClass = 'mb-2 block text-sm font-semibold text-slate-700 dark:text-slate-200';

const buildInitialValues = (currentUser: any): IntakeForm => ({
  fullName: [currentUser?.firstName, currentUser?.lastName].filter(Boolean).join(' ') || '',
  contactPhone: currentUser?.phoneNumber || '',
  deviceType: 'phone',
  deviceBrand: '',
  deviceModel: '',
  deviceColor: '',
  accessoriesReceived: '',
  deviceCondition: '',
  problemDescription: '',
  paymentProvider: 'transfermovil',
  depositAmount: '',
  acceptsMarketing: true,
  source: 'public_web',
});

const RepairIntakePage = () => {
  const { currentUser } = useAppSelector((state) => state.auth);
  const [form, setForm] = useState<IntakeForm>(buildInitialValues(currentUser));
  const [recentOrders, setRecentOrders] = useState<RecentOrder[]>([]);
  const [selectedOrderId, setSelectedOrderId] = useState<string>('');
  const [result, setResult] = useState<IntakeResult | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isLoadingOrders, setIsLoadingOrders] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    setForm((previous) => ({ ...previous, ...buildInitialValues(currentUser), problemDescription: previous.problemDescription }));
  }, [currentUser]);

  const selectedOrder = useMemo(
    () => recentOrders.find((order) => order.id === selectedOrderId) || recentOrders[0],
    [recentOrders, selectedOrderId]
  );

  const fetchRecentOrders = async () => {
    setIsLoadingOrders(true);
    try {
      const response = await axios.get('repair-intake');
      const rows = Array.isArray(response.data?.rows) ? response.data.rows : [];
      setRecentOrders(rows);
      if (rows[0]?.id) setSelectedOrderId(rows[0].id);
    } catch (fetchError: any) {
      console.error('Failed to load repair intake orders:', fetchError);
      setError(fetchError?.response?.data?.message || 'No se pudo cargar el historial de pedidos.');
    } finally {
      setIsLoadingOrders(false);
    }
  };

  useEffect(() => {
    fetchRecentOrders();
  }, []);

  const setField = (field: keyof IntakeForm, value: string | boolean) => {
    setForm((previous) => ({ ...previous, [field]: value }));
  };

  const submitIntake = async (event: React.FormEvent) => {
    event.preventDefault();
    setError('');
    setResult(null);
    setIsSubmitting(true);

    try {
      const response = await axios.post('repair-intake', {
        data: {
          ...form,
          depositAmount: form.depositAmount ? Number(form.depositAmount) : null,
        },
      });
      setResult(response.data);
      setForm((previous) => ({
        ...buildInitialValues(currentUser),
        fullName: previous.fullName,
        contactPhone: previous.contactPhone,
        paymentProvider: previous.paymentProvider,
      }));
      await fetchRecentOrders();
    } catch (submitError: any) {
      console.error('Failed to create repair intake:', submitError);
      setError(submitError?.response?.data?.message || 'No se pudo crear el pedido. Revisa los datos e intenta de nuevo.');
    } finally {
      setIsSubmitting(false);
    }
  };

  const whatsappHref = result
    ? `https://wa.me/5359177041?text=${encodeURIComponent(result.whatsapp.message_body)}`
    : 'https://wa.me/5359177041';

  return (
    <>
      <Head>
        <title>{getPageTitle('Crear pedido de reparación')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiCellphoneCog} title="Pedido rápido de reparación" main>
          <BaseButton href="/repair_orders/repair_orders-list" label="Panel admin" color="info" small />
        </SectionTitleLineWithButton>

        <div className="grid gap-6 xl:grid-cols-[minmax(0,1.35fr)_minmax(360px,0.65fr)]">
          <CardBox className="overflow-hidden border-0 bg-gradient-to-br from-slate-950 via-cyan-950 to-fuchsia-950 text-white shadow-2xl shadow-cyan-900/20">
            <div className="mb-8 rounded-3xl border border-white/10 bg-white/10 p-5 backdrop-blur">
              <div className="mb-3 flex flex-wrap items-center gap-3">
                <span className="rounded-full bg-cyan-400/20 px-3 py-1 text-xs font-bold uppercase tracking-[0.22em] text-cyan-100">Floresoftware Ideas</span>
                <span className="rounded-full bg-fuchsia-400/20 px-3 py-1 text-xs font-semibold text-fuchsia-100">Transfermóvil + Enzona</span>
              </div>
              <h2 className="text-3xl font-black tracking-tight md:text-4xl">Crea una orden, genera referencia de pago y cola de WhatsApp.</h2>
              <p className="mt-3 max-w-3xl text-sm leading-6 text-cyan-50/80">
                Este flujo captura los datos esenciales del cliente y del móvil, abre el pedido, deja el pago pendiente y prepara el mensaje para enviar al WhatsApp del taller.
              </p>
            </div>

            {error && (
              <div className="mb-5 rounded-2xl border border-red-300/40 bg-red-500/15 p-4 text-sm text-red-50" role="alert">
                {error}
              </div>
            )}

            {result && (
              <div className="mb-6 rounded-3xl border border-emerald-300/50 bg-emerald-400/15 p-5 text-emerald-50" role="status">
                <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                  <div>
                    <p className="text-xs font-bold uppercase tracking-[0.2em] text-emerald-100">Pedido creado</p>
                    <h3 className="mt-1 text-2xl font-black">{result.order.order_number}</h3>
                    <p className="mt-1 text-sm text-emerald-50/80">
                      Pago: {result.payment.provider_label} · Referencia {result.payment.reference_code} · WhatsApp {result.whatsapp.status}
                    </p>
                  </div>
                  <BaseButton href={whatsappHref} target="_blank" label="Enviar a WhatsApp" color="success" icon={mdiWhatsapp} />
                </div>
              </div>
            )}

            <form onSubmit={submitIntake} className="grid gap-5 md:grid-cols-2">
              <div>
                <label className="mb-2 block text-sm font-semibold text-cyan-50">Nombre del cliente</label>
                <input className={fieldClass} value={form.fullName} onChange={(event) => setField('fullName', event.target.value)} placeholder="Ej. Ana Flores" required />
              </div>
              <div>
                <label className="mb-2 block text-sm font-semibold text-cyan-50">Teléfono / WhatsApp</label>
                <input className={fieldClass} value={form.contactPhone} onChange={(event) => setField('contactPhone', event.target.value)} placeholder="Ej. +53 59177041" required />
              </div>
              <div>
                <label className="mb-2 block text-sm font-semibold text-cyan-50">Tipo de equipo</label>
                <select className={fieldClass} value={form.deviceType} onChange={(event) => setField('deviceType', event.target.value)}>
                  <option value="phone">Móvil</option>
                  <option value="tablet">Tablet</option>
                  <option value="laptop">Laptop</option>
                  <option value="other">Otro</option>
                </select>
              </div>
              <div>
                <label className="mb-2 block text-sm font-semibold text-cyan-50">Fuente</label>
                <select className={fieldClass} value={form.source} onChange={(event) => setField('source', event.target.value)}>
                  <option value="public_web">Web pública</option>
                  <option value="qr">Código QR</option>
                </select>
              </div>
              <div>
                <label className="mb-2 block text-sm font-semibold text-cyan-50">Marca</label>
                <input className={fieldClass} value={form.deviceBrand} onChange={(event) => setField('deviceBrand', event.target.value)} placeholder="Samsung, Xiaomi, iPhone..." required />
              </div>
              <div>
                <label className="mb-2 block text-sm font-semibold text-cyan-50">Modelo</label>
                <input className={fieldClass} value={form.deviceModel} onChange={(event) => setField('deviceModel', event.target.value)} placeholder="A52, Redmi Note 12, 11 Pro..." required />
              </div>
              <div>
                <label className="mb-2 block text-sm font-semibold text-cyan-50">Color</label>
                <input className={fieldClass} value={form.deviceColor} onChange={(event) => setField('deviceColor', event.target.value)} placeholder="Negro, azul, dorado..." />
              </div>
              <div>
                <label className="mb-2 block text-sm font-semibold text-cyan-50">Accesorios recibidos</label>
                <input className={fieldClass} value={form.accessoriesReceived} onChange={(event) => setField('accessoriesReceived', event.target.value)} placeholder="Cargador, funda, SIM..." />
              </div>
              <div className="md:col-span-2">
                <label className="mb-2 block text-sm font-semibold text-cyan-50">Estado físico visible</label>
                <input className={fieldClass} value={form.deviceCondition} onChange={(event) => setField('deviceCondition', event.target.value)} placeholder="Pantalla rota, mojado, no enciende, golpes..." />
              </div>
              <div className="md:col-span-2">
                <label className="mb-2 block text-sm font-semibold text-cyan-50">Problema a reparar</label>
                <textarea className={`${fieldClass} min-h-[132px]`} value={form.problemDescription} onChange={(event) => setField('problemDescription', event.target.value)} placeholder="Cuéntanos qué pasó, desde cuándo falla y qué intentaste hacer." required minLength={12} />
              </div>

              <div className="md:col-span-2">
                <p className="mb-3 text-sm font-semibold text-cyan-50">Pasarela de pago preferida</p>
                <div className="grid gap-3 md:grid-cols-2">
                  {paymentProviders.map((provider) => (
                    <button
                      key={provider.value}
                      type="button"
                      onClick={() => setField('paymentProvider', provider.value)}
                      className={`rounded-3xl border p-4 text-left transition ${form.paymentProvider === provider.value ? 'border-cyan-300 bg-cyan-300/20 shadow-lg shadow-cyan-500/20' : 'border-white/10 bg-white/10 hover:border-white/30'}`}
                    >
                      <span className="flex items-center gap-2 text-lg font-black"><span>●</span>{provider.label}</span>
                      <span className="mt-2 block text-sm leading-5 text-cyan-50/75">{provider.helper}</span>
                    </button>
                  ))}
                </div>
              </div>

              <div>
                <label className="mb-2 block text-sm font-semibold text-cyan-50">Depósito estimado en CUP (opcional)</label>
                <input className={fieldClass} value={form.depositAmount} onChange={(event) => setField('depositAmount', event.target.value)} placeholder="Ej. 500" type="number" min="0" />
              </div>
              <label className="flex items-center gap-3 rounded-2xl border border-white/10 bg-white/10 px-4 py-3 text-sm text-cyan-50">
                <input type="checkbox" checked={form.acceptsMarketing} onChange={(event) => setField('acceptsMarketing', event.target.checked)} className="h-5 w-5 rounded border-white/20 text-cyan-500 focus:ring-cyan-300" />
                Acepta recibir avisos del pedido y promociones por WhatsApp.
              </label>

              <div className="md:col-span-2 flex flex-col gap-3 pt-2 sm:flex-row">
                <BaseButton type="submit" label={isSubmitting ? 'Creando pedido...' : 'Crear pedido y referencia de pago'} color="success" icon={mdiClipboardCheckOutline} disabled={isSubmitting} />
                <BaseButton href="/qr_links/qr_links-list" label="Ver QR existentes" color="info" icon={mdiQrcodeScan} outline />
              </div>
            </form>
          </CardBox>

          <div className="space-y-6">
            <CardBox className="border-0 bg-white shadow-xl shadow-slate-200/60 dark:bg-dark-900 dark:shadow-none">
              <div className="mb-4 flex items-center justify-between gap-3">
                <div>
                  <p className="text-xs font-bold uppercase tracking-[0.2em] text-cyan-500">Historial</p>
                  <h3 className="text-2xl font-black text-slate-900 dark:text-white">Mis últimos pedidos</h3>
                </div>
                <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-bold text-slate-500 dark:bg-dark-800">{recentOrders.length}</span>
              </div>

              {isLoadingOrders && <p className="rounded-2xl bg-slate-50 p-4 text-sm text-slate-500 dark:bg-dark-800">Cargando pedidos...</p>}

              {!isLoadingOrders && recentOrders.length === 0 && (
                <div className="rounded-3xl border border-dashed border-slate-300 p-6 text-center dark:border-dark-700">
                  <p className="text-lg font-bold text-slate-800 dark:text-slate-100">Aún no hay pedidos.</p>
                  <p className="mt-2 text-sm text-slate-500">Crea el primero y aparecerá aquí con su referencia de pago y estado.</p>
                </div>
              )}

              <div className="space-y-3">
                {recentOrders.map((order) => (
                  <button
                    key={order.id}
                    type="button"
                    onClick={() => setSelectedOrderId(order.id)}
                    className={`w-full rounded-3xl border p-4 text-left transition ${selectedOrder?.id === order.id ? 'border-cyan-300 bg-cyan-50 dark:border-cyan-700 dark:bg-cyan-950/30' : 'border-slate-200 hover:border-cyan-200 dark:border-dark-700 dark:hover:border-cyan-900'}`}
                  >
                    <div className="flex items-start justify-between gap-3">
                      <div>
                        <p className="font-black text-slate-900 dark:text-white">{order.order_number}</p>
                        <p className="mt-1 text-sm text-slate-500">{order.device?.brand} {order.device?.model}</p>
                      </div>
                      <span className="rounded-full bg-fuchsia-100 px-3 py-1 text-xs font-bold text-fuchsia-700 dark:bg-fuchsia-950 dark:text-fuchsia-200">{statusLabels[order.status] || order.status}</span>
                    </div>
                  </button>
                ))}
              </div>
            </CardBox>

            <CardBox className="border-0 bg-slate-950 text-white shadow-xl shadow-slate-900/20">
              <div className="mb-4 flex items-center gap-3">
                <div className="rounded-2xl bg-cyan-400/20 p-3 text-cyan-100"><span className="sr-only">Pago</span><svg className="h-5 w-5" viewBox="0 0 24 24" fill="currentColor"><path d={mdiCreditCardOutline} /></svg></div>
                <div>
                  <p className="text-xs font-bold uppercase tracking-[0.2em] text-cyan-300">Detalle</p>
                  <h3 className="text-xl font-black">Pedido seleccionado</h3>
                </div>
              </div>

              {selectedOrder ? (
                <div className="space-y-4 text-sm text-slate-200">
                  <div className="rounded-3xl bg-white/10 p-4">
                    <p className="text-xs uppercase tracking-[0.18em] text-cyan-200">Problema</p>
                    <p className="mt-2 leading-6">{selectedOrder.problem_description}</p>
                  </div>
                  <div className="grid gap-3 sm:grid-cols-2">
                    <div className="rounded-2xl bg-white/10 p-4">
                      <p className="text-xs text-slate-400">Pago</p>
                      <p className="mt-1 font-bold">{selectedOrder.payments_repair_order?.[0]?.payment_method?.display_name || 'Pendiente'}</p>
                    </div>
                    <div className="rounded-2xl bg-white/10 p-4">
                      <p className="text-xs text-slate-400">Referencia</p>
                      <p className="mt-1 font-bold">{selectedOrder.payments_repair_order?.[0]?.reference_code || 'Sin referencia'}</p>
                    </div>
                    <div className="rounded-2xl bg-white/10 p-4">
                      <p className="text-xs text-slate-400">WhatsApp</p>
                      <p className="mt-1 font-bold">{selectedOrder.whatsapp_notifications_repair_order?.[0]?.status || 'Sin cola'}</p>
                    </div>
                    <div className="rounded-2xl bg-white/10 p-4">
                      <p className="text-xs text-slate-400">Creado</p>
                      <p className="mt-1 font-bold">{new Date(selectedOrder.createdAt).toLocaleDateString()}</p>
                    </div>
                  </div>
                  <BaseButton href={`/repair_orders/${selectedOrder.id}`} label="Abrir detalle CRUD" color="info" outline />
                </div>
              ) : (
                <p className="rounded-3xl border border-dashed border-white/20 p-5 text-slate-300">Selecciona o crea un pedido para ver su detalle.</p>
              )}
            </CardBox>
          </div>
        </div>
      </SectionMain>
    </>
  );
};

RepairIntakePage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};

export default RepairIntakePage;
