'use client';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { api } from '@/lib/api';
import { useLanguage } from '@/lib/language-context';
import { Plus, Trash2 } from 'lucide-react';
import React, { useEffect, useState } from 'react';

type DocumentType = 'Prescription' | 'Referral' | 'Certification' | 'Medical Leave' | 'Laboratory' | 'Imaging';

interface Medication {
  name: string;
  dosage: string;
  frequency: string;
  duration: string;
  instructions: string;
}

interface PrescriptionData {
  _id?: string;
  documentType: DocumentType;
  medications: Medication[];
  diagnosis: string;
  freeText: string;
  notes: string;
}

interface PrescriptionFormProps {
  patientId: string;
  initialData?: any;
  onSuccess?: () => void;
  onCancel?: () => void;
}

const DOCUMENT_TYPES: { value: DocumentType; labelKey: string }[] = [
  { value: 'Prescription', labelKey: 'prescriptions.documentTypePrescription' },
  { value: 'Referral', labelKey: 'prescriptions.documentTypeReferral' },
  { value: 'Certification', labelKey: 'prescriptions.documentTypeCertification' },
  { value: 'Medical Leave', labelKey: 'prescriptions.documentTypeMedicalLeave' },
  { value: 'Laboratory', labelKey: 'prescriptions.documentTypeLaboratory' },
  { value: 'Imaging', labelKey: 'prescriptions.documentTypeImaging' },
];

export default function PrescriptionForm({ patientId, initialData, onSuccess, onCancel }: PrescriptionFormProps) {
  const { t } = useLanguage();
  const [loading, setLoading] = useState(false);

  const [formData, setFormData] = useState<{
    documentType: DocumentType;
    diagnosis: string;
    freeText: string;
    notes: string;
    medications: Medication[];
  }>({
    documentType: 'Prescription',
    diagnosis: '',
    freeText: '',
    notes: '',
    medications: [{ name: '', dosage: '', frequency: '', duration: '', instructions: '' }],
  });

  useEffect(() => {
    if (initialData) {
      setFormData({
        documentType: initialData.documentType || 'Prescription',
        diagnosis: initialData.diagnosis || '',
        freeText: initialData.freeText || '',
        notes: initialData.notes || '',
        medications: Array.isArray(initialData.medications) && initialData.medications.length > 0
          ? initialData.medications.map((m: any) => ({
            name: m.name || '',
            dosage: m.dosage || '',
            frequency: m.frequency || '',
            duration: m.duration || '',
            instructions: m.instructions || ''
          }))
          : [{ name: '', dosage: '', frequency: '', duration: '', instructions: '' }],
      });
    }
  }, [initialData]);

  const isPrescription = formData.documentType === 'Prescription';

  const handleMedicationChange = (index: number, field: keyof Medication, value: string) => {
    const updatedMedications = [...formData.medications];
    updatedMedications[index] = { ...updatedMedications[index], [field]: value };
    setFormData({ ...formData, medications: updatedMedications });
  };

  const addMedication = () => {
    setFormData({
      ...formData,
      medications: [...formData.medications, { name: '', dosage: '', frequency: '', duration: '', instructions: '' }]
    });
  };

  const removeMedication = (index: number) => {
    if (formData.medications.length === 1) return;
    setFormData({ ...formData, medications: formData.medications.filter((_, i) => i !== index) });
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e: React.SyntheticEvent<HTMLFormElement>) => {
    e.preventDefault();
    setLoading(true);

    try {
      const validMedications = isPrescription
        ? formData.medications.filter(m => m.name.trim() !== '')
        : [];

      const payload = {
        patientId,
        documentType: formData.documentType,
        medications: validMedications,
        diagnosis: formData.diagnosis,
        freeText: formData.freeText,
        notes: formData.notes,
      };

      let response;
      if (initialData?._id) {
        response = await api.prescriptions.update(initialData._id, payload);
      } else {
        response = await api.prescriptions.create(payload);
      }

      if (response.success) {
        onSuccess?.();
      } else {
        console.error('Failed to save prescription:', response.error);
      }
    } catch (error) {
      console.error('Error saving prescription:', error);
    } finally {
      setLoading(false);
    }
  };

  const isEditing = !!initialData?._id;

  return (
    <div className="space-y-6 md:space-y-10 p-4 md:p-8 bg-white rounded-xl shadow-lg border border-slate-100">
      <div className="flex justify-between items-center border-b-2 border-slate-100 pb-4">
        <h1 className="text-2xl md:text-3xl font-bold text-slate-800">
          {isEditing ? t('prescriptions.editPrescription') : t('prescriptions.createPrescription')}
        </h1>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Document Type */}
        <div className="space-y-2">
          <Label className="text-base font-semibold text-slate-700" htmlFor="documentType">
            {t('prescriptions.documentType')}
          </Label>
          <div className="flex flex-wrap gap-2">
            {DOCUMENT_TYPES.map(({ value, labelKey }) => (
              <button
                key={value}
                type="button"
                onClick={() => setFormData({ ...formData, documentType: value })}
                className={`px-4 py-2 rounded-full border text-sm font-medium transition-colors ${
                  formData.documentType === value
                    ? 'bg-slate-800 text-white border-slate-800'
                    : 'bg-white text-slate-600 border-slate-300 hover:border-slate-500'
                }`}
              >
                {t(labelKey as any)}
              </button>
            ))}
          </div>
        </div>

        {/* Diagnosis (always visible) */}
        <div className="space-y-2">
          <Label className="text-base font-semibold text-slate-700" htmlFor="diagnosis">{t('prescriptions.diagnosis')}</Label>
          <Input
            id="diagnosis"
            name="diagnosis"
            placeholder={t('prescriptions.diagnosisPlaceholder')}
            value={formData.diagnosis}
            onChange={handleChange}
            className="h-11"
          />
        </div>

        {/* Medications — only for Prescription type */}
        {isPrescription && (
          <div className="space-y-4">
            <Label className="text-base font-semibold text-slate-700">{t('prescriptions.medication')}</Label>

            {formData.medications.map((medication, index) => (
              <div key={index} className="p-4 border rounded-lg bg-slate-50 relative group">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                  <div className="space-y-2">
                    <Label className="text-sm">{t('prescriptions.medication')}</Label>
                    <Input
                      value={medication.name}
                      onChange={(e) => handleMedicationChange(index, 'name', e.target.value)}
                      placeholder={t('prescriptions.medicationNamePlaceholder')}
                      className="bg-white"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-sm">{t('prescriptions.dosage')}</Label>
                    <Input
                      value={medication.dosage}
                      onChange={(e) => handleMedicationChange(index, 'dosage', e.target.value)}
                      placeholder={t('prescriptions.dosagePlaceholder')}
                      className="bg-white"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="space-y-2">
                    <Label className="text-sm">{t('prescriptions.frequency')}</Label>
                    <Input
                      value={medication.frequency}
                      onChange={(e) => handleMedicationChange(index, 'frequency', e.target.value)}
                      placeholder={t('prescriptions.frequencyPlaceholder')}
                      className="bg-white"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-sm">{t('prescriptions.duration')}</Label>
                    <Input
                      value={medication.duration}
                      onChange={(e) => handleMedicationChange(index, 'duration', e.target.value)}
                      placeholder={t('prescriptions.durationPlaceholder')}
                      className="bg-white"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-sm">{t('prescriptions.instructions')}</Label>
                    <Input
                      value={medication.instructions}
                      onChange={(e) => handleMedicationChange(index, 'instructions', e.target.value)}
                      placeholder={t('prescriptions.instructionsPlaceholder')}
                      className="bg-white"
                    />
                  </div>
                </div>

                {formData.medications.length > 1 && (
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    onClick={() => removeMedication(index)}
                    className="absolute top-2 right-2 text-slate-400 hover:text-red-500"
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                )}
              </div>
            ))}

            <Button
              type="button"
              variant="outline"
              onClick={addMedication}
              className="w-full border-dashed"
            >
              <Plus className="mr-2 h-4 w-4" /> {t('common.add')} {t('prescriptions.medication')}
            </Button>
          </div>
        )}

        {/* Free text — for Referral, Certification, Medical Leave, Laboratory, Imaging */}
        {!isPrescription && (
          <div className="space-y-2">
            <Label className="text-base font-semibold text-slate-700" htmlFor="freeText">
              {t('prescriptions.freeText')}
            </Label>
            <Textarea
              id="freeText"
              name="freeText"
              placeholder={t('prescriptions.freeTextPlaceholder')}
              value={formData.freeText}
              onChange={handleChange}
              className="bg-slate-50 min-h-48"
            />
          </div>
        )}

        {/* Additional Notes */}
        <div className="space-y-2">
          <Label className="text-base font-semibold text-slate-700" htmlFor="notes">{t('prescriptions.notes')}</Label>
          <Textarea
            id="notes"
            name="notes"
            placeholder={t('prescriptions.notesPlaceholder')}
            value={formData.notes}
            onChange={handleChange}
            className="bg-slate-50 min-h-20"
          />
        </div>

        {/* Actions */}
        <div className="flex justify-end gap-3 pt-6 border-t border-slate-100">
          {onCancel && (
            <Button type="button" variant="outline" onClick={onCancel}>
              {t('common.cancel')}
            </Button>
          )}
          <Button type="submit" disabled={loading}>
            {loading
              ? t('prescriptions.creating')
              : isEditing ? t('prescriptions.updateButton') : t('prescriptions.createButton')
            }
          </Button>
        </div>
      </form>
    </div>
  );
}
