'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useApi } from '@/lib/useApi';
import {
  getMedicine,
  listMedicineProducts,
  createMedicineProduct,
  deleteMedicineProduct,
  updateMedicine,
  updateMedicineProduct,
} from '@/services/medicines';
import { listCabinetItems, adjustCabinetItemQuantity, deleteCabinetItem } from '@/services/cabinet';
import {
  DosageUnit,
  ConcentrationUnit,
  MedicineForm,
  StrengthUnit,
  MedicineCategory,
  MedicineProductSource,
  allowedUnitsForForm,
  defaultUnitForForm,
  type CreateMedicineProductInput,
  type UpdateMedicineInput,
  type UpdateMedicineProductInput,
} from '@meshitrack/shared';

type MedicineDetail = {
  _id: string;
  name: string;
  form: string;
  strength: number;
  strengthUnit: string;
  category: string;
  notes?: string;
  tags: string[];
  createdAt: string;
  updatedAt: string;
};

type MedicineProduct = {
  _id: string;
  brand: string;
  manufacturer?: string;
  packageSize: number;
  packageUnit: string;
  concentration?: number;
  concentrationUnit?: string;
  notes?: string;
  source: string;
};

type CabinetItemDetail = {
  _id: string;
  medicineProductBrand?: string;
  concentration?: number;
  concentrationUnit?: string;
  quantity: number;
  unit: string;
  expirationDate?: string;
  status: string;
  notes?: string;
};

const FORM_LABELS: Record<string, string> = {
  tablet: 'Tablet',
  capsule: 'Capsule',
  liquid: 'Liquid',
  injection: 'Injection',
  other: 'Other',
};

const CATEGORY_LABELS: Record<string, string> = {
  prescription: 'Prescription',
  otc: 'OTC',
  supplement: 'Supplement',
  other: 'Other',
};

const CATEGORY_COLORS: Record<string, string> = {
  prescription: 'bg-blue-100 text-blue-700',
  otc: 'bg-green-100 text-green-700',
  supplement: 'bg-purple-100 text-purple-700',
  other: 'bg-gray-100 text-gray-700',
};

const UNIT_LABELS: Record<string, string> = {
  tablet: 'tablets',
  capsule: 'capsules',
  ml: 'mL',
  vial: 'vials',
  dose: 'doses',
};

const STATUS_COLORS: Record<string, string> = {
  active: 'bg-green-100 text-green-700',
  depleted: 'bg-gray-100 text-gray-600',
  expired: 'bg-red-100 text-red-700',
};

export default function MedicineDetailPage() {
  const params = useParams<{ id: string }>();
  const { householdId, isLoading: sessionLoading } = useApi();
  const [medicine, setMedicine] = useState<MedicineDetail | null>(null);
  const [products, setProducts] = useState<MedicineProduct[]>([]);
  const [cabinetItems, setCabinetItems] = useState<CabinetItemDetail[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showProductForm, setShowProductForm] = useState(false);
  const [editingMedicine, setEditingMedicine] = useState(false);
  const [medicineForm, setMedicineForm] = useState<UpdateMedicineInput>({});
  const [medicineSubmitting, setMedicineSubmitting] = useState(false);
  const [editingProductId, setEditingProductId] = useState<string | null>(null);
  const [productForm, setProductForm] = useState<UpdateMedicineProductInput>({});
  const [productSubmitting, setProductSubmitting] = useState(false);

  function startEditMedicine() {
    if (!medicine) return;
    setMedicineForm({
      name: medicine.name,
      form: medicine.form as MedicineForm,
      strength: medicine.strength,
      strengthUnit: medicine.strengthUnit as StrengthUnit,
      category: medicine.category as MedicineCategory,
      notes: medicine.notes ?? undefined,
      tags: [...medicine.tags],
    });
    setEditingMedicine(true);
  }

  function cancelEditMedicine() {
    setEditingMedicine(false);
    setMedicineForm({});
  }

  async function handleSaveMedicine(e: React.FormEvent) {
    e.preventDefault();
    if (!householdId || !medicine) return;
    setMedicineSubmitting(true);
    setError('');
    try {
      const updated = await updateMedicine(householdId, medicine._id, {
        ...medicineForm,
        name: medicineForm.name?.trim(),
        strength: Number(medicineForm.strength),
      });
      setMedicine(updated as unknown as MedicineDetail);
      setEditingMedicine(false);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to update medicine');
    } finally {
      setMedicineSubmitting(false);
    }
  }

  function startEditProduct(product: MedicineProduct) {
    setEditingProductId(product._id);
    const validUnits = Object.values(DosageUnit) as string[];
    const allowedUnits = allowedUnitsForForm(
      (medicine?.form as MedicineForm) ?? MedicineForm.OTHER,
    );
    const storedUnit = product.packageUnit;
    const packageUnit = validUnits.includes(storedUnit)
      ? (storedUnit as DosageUnit)
      : allowedUnits[0];
    setProductForm({
      brand: product.brand,
      manufacturer: product.manufacturer ?? undefined,
      packageSize: product.packageSize,
      packageUnit,
      concentration: product.concentration ?? undefined,
      concentrationUnit: product.concentrationUnit as ConcentrationUnit | undefined,
      notes: product.notes ?? undefined,
    });
  }

  function cancelEditProduct() {
    setEditingProductId(null);
    setProductForm({});
  }

  async function handleSaveProduct(e: React.FormEvent) {
    e.preventDefault();
    if (!householdId || !editingProductId) return;
    setProductSubmitting(true);
    setError('');
    try {
      const updated = await updateMedicineProduct(householdId, editingProductId, {
        ...productForm,
        brand: productForm.brand?.trim(),
        packageSize: Number(productForm.packageSize),
      });
      setProducts((prev) =>
        prev.map((p) => (p._id === editingProductId ? (updated as unknown as MedicineProduct) : p)),
      );
      setEditingProductId(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to update product');
    } finally {
      setProductSubmitting(false);
    }
  }

  const fetchData = useCallback(async () => {
    if (!householdId || !params.id) return;
    setLoading(true);
    try {
      const [med, prods, cabinet] = await Promise.all([
        getMedicine(householdId, params.id),
        listMedicineProducts(householdId, params.id, { limit: 50 }),
        listCabinetItems(householdId, { medicineId: params.id, limit: 50 }),
      ]);
      setMedicine(med);
      setProducts(prods.data);
      setCabinetItems(cabinet.data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load medicine');
    } finally {
      setLoading(false);
    }
  }, [householdId, params.id]);

  useEffect(() => {
    if (householdId) {
      fetchData();
    }
  }, [householdId, fetchData]);

  async function handleDeleteProduct(productId: string, brand: string) {
    if (!householdId || !confirm(`Delete product "${brand}"?`)) return;
    try {
      await deleteMedicineProduct(householdId, productId);
      setProducts((prev) => prev.filter((p) => p._id !== productId));
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to delete product');
    }
  }

  async function handleAdjustCabinet(itemId: string, delta: number) {
    if (!householdId) return;
    try {
      await adjustCabinetItemQuantity(householdId, itemId, { delta });
      fetchData();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to adjust quantity');
    }
  }

  async function handleDeleteCabinet(itemId: string) {
    if (!householdId || !confirm('Delete this cabinet item?')) return;
    try {
      await deleteCabinetItem(householdId, itemId);
      fetchData();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to delete cabinet item');
    }
  }

  if (sessionLoading || loading) {
    return <PageSkeleton />;
  }

  if (error && !medicine) {
    return (
      <div>
        <BackLink />
        <div className="rounded-xl border bg-white p-6 shadow-sm">
          <p className="text-red-600">{error}</p>
        </div>
      </div>
    );
  }

  if (!medicine) return null;

  return (
    <div>
      <BackLink />

      {error && (
        <div className="mb-4 rounded-lg bg-red-50 border border-red-200 p-3 text-sm text-red-700">
          {error}
          <button onClick={() => setError('')} className="ml-2 underline">
            Dismiss
          </button>
        </div>
      )}

      {/* Medicine details card */}
      {editingMedicine ? (
        <div className="mb-6 rounded-xl border bg-white p-6 shadow-sm">
          <h2 className="text-lg font-semibold mb-4">Edit Medicine</h2>
          <form onSubmit={handleSaveMedicine} className="space-y-4">
            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Name</label>
                <input
                  type="text"
                  required
                  maxLength={200}
                  value={medicineForm.name ?? ''}
                  onChange={(e) => setMedicineForm({ ...medicineForm, name: e.target.value })}
                  className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Form</label>
                <select
                  value={medicineForm.form ?? ''}
                  onChange={(e) =>
                    setMedicineForm({ ...medicineForm, form: e.target.value as MedicineForm })
                  }
                  className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                >
                  {Object.values(MedicineForm).map((f) => (
                    <option key={f} value={f}>
                      {FORM_LABELS[f] ?? f}
                    </option>
                  ))}
                </select>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Strength</label>
                  <input
                    type="number"
                    required
                    min={0.01}
                    step="any"
                    value={medicineForm.strength ?? ''}
                    onChange={(e) =>
                      setMedicineForm({ ...medicineForm, strength: Number(e.target.value) })
                    }
                    className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Unit</label>
                  <select
                    value={medicineForm.strengthUnit ?? ''}
                    onChange={(e) =>
                      setMedicineForm({
                        ...medicineForm,
                        strengthUnit: e.target.value as StrengthUnit,
                      })
                    }
                    className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                  >
                    {Object.values(StrengthUnit).map((u) => (
                      <option key={u} value={u}>
                        {u}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Category</label>
                <select
                  value={medicineForm.category ?? ''}
                  onChange={(e) =>
                    setMedicineForm({
                      ...medicineForm,
                      category: e.target.value as MedicineCategory,
                    })
                  }
                  className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                >
                  {Object.values(MedicineCategory).map((c) => (
                    <option key={c} value={c}>
                      {CATEGORY_LABELS[c] ?? c}
                    </option>
                  ))}
                </select>
              </div>
              <div className="md:col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Notes (optional)
                </label>
                <input
                  type="text"
                  maxLength={1000}
                  value={medicineForm.notes ?? ''}
                  onChange={(e) =>
                    setMedicineForm({ ...medicineForm, notes: e.target.value || undefined })
                  }
                  className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                />
              </div>
              <div className="md:col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Tags (comma-separated)
                </label>
                <input
                  type="text"
                  maxLength={500}
                  value={(medicineForm.tags ?? []).join(', ')}
                  onChange={(e) =>
                    setMedicineForm({
                      ...medicineForm,
                      tags: e.target.value
                        .split(',')
                        .map((t) => t.trim())
                        .filter(Boolean),
                    })
                  }
                  placeholder="e.g. daily, morning"
                  className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                />
              </div>
            </div>
            <div className="flex gap-3 pt-2">
              <button
                type="submit"
                disabled={medicineSubmitting}
                className="rounded-lg bg-primary-600 px-4 py-2 text-sm font-medium text-white hover:bg-primary-700 disabled:opacity-50 transition-colors"
              >
                {medicineSubmitting ? 'Saving...' : 'Save'}
              </button>
              <button
                type="button"
                onClick={cancelEditMedicine}
                className="rounded-lg border px-4 py-2 text-sm font-medium hover:bg-gray-50 transition-colors"
              >
                Cancel
              </button>
            </div>
          </form>
        </div>
      ) : (
        <div className="mb-6 rounded-xl border bg-white p-6 shadow-sm">
          <div className="flex items-start justify-between">
            <div>
              <div className="flex items-center gap-2">
                <h1 className="text-2xl font-bold">{medicine.name}</h1>
                <button
                  onClick={startEditMedicine}
                  className="rounded p-1 text-gray-400 hover:text-primary-600 hover:bg-primary-50 transition-colors"
                  title="Edit"
                >
                  <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"
                    />
                  </svg>
                </button>
              </div>
              <p className="mt-1 text-gray-500">
                {medicine.strength} {medicine.strengthUnit}{' '}
                {FORM_LABELS[medicine.form] ?? medicine.form}
              </p>
              {medicine.notes && <p className="mt-2 text-sm text-gray-500">{medicine.notes}</p>}
            </div>
            <span
              className={`rounded-full px-3 py-1 text-xs font-medium ${CATEGORY_COLORS[medicine.category] ?? CATEGORY_COLORS['other']}`}
            >
              {CATEGORY_LABELS[medicine.category] ?? medicine.category}
            </span>
          </div>
        </div>
      )}

      {/* Inventory section */}
      <div className="mb-4">
        <h2 className="text-lg font-semibold mb-3">Inventory</h2>
        {cabinetItems.length === 0 ? (
          <div className="rounded-xl border bg-white p-6 shadow-sm text-center text-gray-500">
            No inventory items.{' '}
            <Link href="/medicines/cabinet" className="text-primary-600 underline">
              Add from cabinet
            </Link>
          </div>
        ) : (
          <div className="space-y-2">
            {cabinetItems.map((item) => (
              <div
                key={item._id}
                className="rounded-lg border bg-white p-3 shadow-sm flex items-center justify-between"
              >
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 text-sm text-gray-600">
                    {item.medicineProductBrand && (
                      <span className="text-gray-500">{item.medicineProductBrand}</span>
                    )}
                    {item.concentration != null && item.concentrationUnit && (
                      <span className="text-gray-400">
                        {item.concentration} {item.concentrationUnit}
                      </span>
                    )}
                  </div>
                  <div className="flex items-center gap-3 mt-1 text-sm">
                    <span className="font-medium">
                      {item.quantity} {UNIT_LABELS[item.unit] ?? item.unit}
                    </span>
                    {item.expirationDate && (
                      <span className="text-gray-500">
                        Exp: {new Date(item.expirationDate).toLocaleDateString()}
                      </span>
                    )}
                  </div>
                  {item.notes && <p className="text-xs text-gray-400 mt-1">{item.notes}</p>}
                </div>
                <div className="flex items-center gap-2 ml-3">
                  <span
                    className={`rounded-full px-2 py-0.5 text-xs font-medium ${STATUS_COLORS[item.status] ?? STATUS_COLORS['active']}`}
                  >
                    {item.status}
                  </span>
                  {item.status === 'active' && (
                    <div className="flex items-center gap-1">
                      <button
                        onClick={() => handleAdjustCabinet(item._id, -1)}
                        className="rounded border px-2 py-1 text-xs font-medium text-gray-600 hover:bg-gray-100 transition-colors"
                        title="Take 1"
                      >
                        -1
                      </button>
                      <button
                        onClick={() => handleAdjustCabinet(item._id, 1)}
                        className="rounded border px-2 py-1 text-xs font-medium text-gray-600 hover:bg-gray-100 transition-colors"
                        title="Add 1"
                      >
                        +1
                      </button>
                    </div>
                  )}
                  <button
                    onClick={() => handleDeleteCabinet(item._id)}
                    className="rounded p-1 text-gray-400 hover:text-red-600 hover:bg-red-50 transition-colors"
                    title="Delete"
                  >
                    <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
                      />
                    </svg>
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Products section */}
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-semibold">Products (Brands/Packages)</h2>
        <button
          onClick={() => setShowProductForm(!showProductForm)}
          className="rounded-lg bg-primary-600 px-4 py-2 text-sm font-medium text-white hover:bg-primary-700 transition-colors"
        >
          {showProductForm ? 'Cancel' : 'Add Product'}
        </button>
      </div>

      {showProductForm && householdId && (
        <CreateProductForm
          householdId={householdId}
          medicineId={params.id}
          /* v8 ignore next */
          medicineForm={(medicine?.form as MedicineForm) ?? MedicineForm.OTHER}
          onCreated={() => {
            setShowProductForm(false);
            fetchData();
          }}
          onCancel={() => setShowProductForm(false)}
        />
      )}

      {products.length === 0 ? (
        <div className="rounded-xl border bg-white p-6 shadow-sm text-center text-gray-500">
          No products yet. Add a specific brand or package above.
        </div>
      ) : (
        <div className="space-y-3">
          {products.map((product) =>
            editingProductId === product._id ? (
              <div key={product._id} className="rounded-xl border bg-white p-4 shadow-sm">
                <form onSubmit={handleSaveProduct} className="space-y-4">
                  <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Brand</label>
                      <input
                        type="text"
                        required
                        maxLength={200}
                        /* v8 ignore next */
                        value={productForm.brand ?? ''}
                        onChange={(e) => setProductForm({ ...productForm, brand: e.target.value })}
                        className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Manufacturer (optional)
                      </label>
                      <input
                        type="text"
                        maxLength={200}
                        value={productForm.manufacturer ?? ''}
                        onChange={(e) =>
                          setProductForm({
                            ...productForm,
                            manufacturer: e.target.value || undefined,
                          })
                        }
                        className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                          Package Size
                        </label>
                        <input
                          type="number"
                          required
                          min={1}
                          step="any"
                          value={/* v8 ignore next */ productForm.packageSize ?? ''}
                          onChange={(e) =>
                            setProductForm({
                              ...productForm,
                              packageSize: Number(e.target.value),
                            })
                          }
                          className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">Unit</label>
                        <select
                          value={/* v8 ignore next */ productForm.packageUnit ?? ''}
                          onChange={(e) =>
                            setProductForm({
                              ...productForm,
                              packageUnit: e.target.value as DosageUnit,
                            })
                          }
                          className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                        >
                          {allowedUnitsForForm(
                            /* v8 ignore next */ (medicine?.form as MedicineForm) ??
                              MedicineForm.OTHER,
                          ).map((u) => (
                            <option key={u} value={u}>
                              {u}
                            </option>
                          ))}
                        </select>
                      </div>
                    </div>
                    {(medicine?.form as MedicineForm) === MedicineForm.INJECTION &&
                      productForm.packageUnit === DosageUnit.ML && (
                        <div className="grid grid-cols-2 gap-3">
                          <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                              Concentration
                            </label>
                            <input
                              type="number"
                              min={0.01}
                              step="any"
                              value={productForm.concentration ?? ''}
                              onChange={(e) =>
                                setProductForm({
                                  ...productForm,
                                  concentration: e.target.value
                                    ? Number(e.target.value)
                                    : undefined,
                                })
                              }
                              placeholder="e.g. 100"
                              className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                            />
                          </div>
                          <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                              Conc. Unit
                            </label>
                            <select
                              value={productForm.concentrationUnit ?? ''}
                              onChange={(e) =>
                                setProductForm({
                                  ...productForm,
                                  concentrationUnit:
                                    (e.target.value as ConcentrationUnit) || undefined,
                                })
                              }
                              className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                            >
                              <option value="">--</option>
                              {Object.values(ConcentrationUnit).map((u) => (
                                <option key={u} value={u}>
                                  {u}
                                </option>
                              ))}
                            </select>
                          </div>
                        </div>
                      )}
                    <div className="md:col-span-2">
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Notes (optional)
                      </label>
                      <input
                        type="text"
                        maxLength={1000}
                        value={productForm.notes ?? ''}
                        onChange={(e) =>
                          setProductForm({
                            ...productForm,
                            notes: e.target.value || undefined,
                          })
                        }
                        className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                      />
                    </div>
                  </div>
                  <div className="flex gap-3 pt-2">
                    <button
                      type="submit"
                      disabled={productSubmitting}
                      className="rounded-lg bg-primary-600 px-4 py-2 text-sm font-medium text-white hover:bg-primary-700 disabled:opacity-50 transition-colors"
                    >
                      {productSubmitting ? 'Saving...' : 'Save'}
                    </button>
                    <button
                      type="button"
                      onClick={cancelEditProduct}
                      className="rounded-lg border px-4 py-2 text-sm font-medium hover:bg-gray-50 transition-colors"
                    >
                      Cancel
                    </button>
                  </div>
                </form>
              </div>
            ) : (
              <div
                key={product._id}
                className="rounded-xl border bg-white p-4 shadow-sm flex items-center justify-between"
              >
                <div>
                  <h3 className="font-medium text-gray-900">{product.brand}</h3>
                  <p className="text-sm text-gray-500">
                    {product.packageSize} {product.packageUnit}
                    {product.concentration && product.concentrationUnit
                      ? ` (${product.concentration} ${product.concentrationUnit})`
                      : ''}
                    {product.manufacturer ? ` - ${product.manufacturer}` : ''}
                  </p>
                  {product.notes && <p className="text-xs text-gray-400 mt-1">{product.notes}</p>}
                </div>
                <div className="flex items-center gap-1">
                  <button
                    onClick={() => startEditProduct(product)}
                    className="rounded p-1 text-gray-400 hover:text-primary-600 hover:bg-primary-50 transition-colors"
                    title="Edit"
                  >
                    <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"
                      />
                    </svg>
                  </button>
                  <button
                    onClick={() => handleDeleteProduct(product._id, product.brand)}
                    className="rounded p-1 text-gray-400 hover:text-red-600 hover:bg-red-50 transition-colors"
                    title="Delete"
                  >
                    <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
                      />
                    </svg>
                  </button>
                </div>
              </div>
            ),
          )}
        </div>
      )}
    </div>
  );
}

function BackLink() {
  return (
    <Link
      href="/medicines/library"
      className="mb-4 inline-flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700 transition-colors"
    >
      <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
      </svg>
      Back to Medicines
    </Link>
  );
}

function PageSkeleton() {
  return (
    <div>
      <div className="mb-4 h-5 w-32 animate-pulse rounded bg-gray-200" />
      <div className="mb-6 animate-pulse rounded-xl border bg-white p-6 shadow-sm h-32" />
      <div className="h-6 w-48 animate-pulse rounded bg-gray-200 mb-4" />
      <div className="animate-pulse rounded-xl border bg-white p-4 h-20" />
    </div>
  );
}

function CreateProductForm({
  householdId,
  medicineId,
  medicineForm,
  onCreated,
  onCancel,
}: {
  householdId: string;
  medicineId: string;
  medicineForm: MedicineForm;
  onCreated: () => void;
  onCancel: () => void;
}) {
  const allowedUnits = allowedUnitsForForm(medicineForm);
  const [formData, setFormData] = useState<CreateMedicineProductInput>({
    brand: '',
    packageSize: 0,
    packageUnit: defaultUnitForForm(medicineForm),
    source: MedicineProductSource.MANUAL,
  });
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError('');
    setSubmitting(true);
    try {
      await createMedicineProduct(householdId, medicineId, {
        ...formData,
        brand: formData.brand.trim(),
        packageSize: Number(formData.packageSize),
      });
      onCreated();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create product');
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="mb-6 rounded-xl border bg-white p-6 shadow-sm">
      <h3 className="text-base font-semibold mb-4">Add Product</h3>
      {error && (
        <div className="mb-4 rounded-lg bg-red-50 border border-red-200 p-3 text-sm text-red-700">
          {error}
        </div>
      )}
      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Brand</label>
            <input
              type="text"
              required
              maxLength={200}
              value={formData.brand}
              onChange={(e) => setFormData({ ...formData, brand: e.target.value })}
              placeholder="e.g. CVS Health"
              className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Manufacturer (optional)
            </label>
            <input
              type="text"
              maxLength={200}
              value={formData.manufacturer ?? ''}
              onChange={(e) =>
                setFormData({ ...formData, manufacturer: e.target.value || undefined })
              }
              placeholder="e.g. Pfizer"
              className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
            />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Package Size</label>
              <input
                type="number"
                required
                min={1}
                step="any"
                value={formData.packageSize || ''}
                onChange={(e) => setFormData({ ...formData, packageSize: Number(e.target.value) })}
                placeholder="90"
                className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Unit</label>
              <select
                value={formData.packageUnit}
                onChange={(e) =>
                  setFormData({ ...formData, packageUnit: e.target.value as DosageUnit })
                }
                className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
              >
                {allowedUnits.map((u) => (
                  <option key={u} value={u}>
                    {u}
                  </option>
                ))}
              </select>
            </div>
          </div>
          {medicineForm === MedicineForm.INJECTION && formData.packageUnit === DosageUnit.ML && (
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Concentration
                </label>
                <input
                  type="number"
                  min={0.01}
                  step="any"
                  value={formData.concentration ?? ''}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      concentration: e.target.value ? Number(e.target.value) : undefined,
                    })
                  }
                  placeholder="e.g. 100"
                  className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Conc. Unit</label>
                <select
                  value={formData.concentrationUnit ?? ''}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      concentrationUnit: (e.target.value as ConcentrationUnit) || undefined,
                    })
                  }
                  className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
                >
                  <option value="">--</option>
                  {Object.values(ConcentrationUnit).map((u) => (
                    <option key={u} value={u}>
                      {u}
                    </option>
                  ))}
                </select>
              </div>
            </div>
          )}
          <div className="md:col-span-2">
            <label className="block text-sm font-medium text-gray-700 mb-1">Notes (optional)</label>
            <input
              type="text"
              maxLength={1000}
              value={formData.notes ?? ''}
              onChange={(e) => setFormData({ ...formData, notes: e.target.value || undefined })}
              placeholder="Any additional notes"
              className="w-full rounded-lg border px-3 py-2 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none"
            />
          </div>
        </div>
        <div className="flex gap-3 pt-2">
          <button
            type="submit"
            disabled={submitting}
            className="rounded-lg bg-primary-600 px-4 py-2 text-sm font-medium text-white hover:bg-primary-700 disabled:opacity-50 transition-colors"
          >
            {submitting ? 'Creating...' : 'Create Product'}
          </button>
          <button
            type="button"
            onClick={onCancel}
            className="rounded-lg border px-4 py-2 text-sm font-medium hover:bg-gray-50 transition-colors"
          >
            Cancel
          </button>
        </div>
      </form>
    </div>
  );
}
