import React, { useState } from 'react';
import { useCreateTicket } from '@/hooks/useCreateTicket';
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Select } from '@/components/ui/Select';
import { Textarea } from '@/components/ui/Textarea';

interface NewTicketWidgetProps {
  onCancel: () => void;
  onSuccess: (ticketId: string) => void;
}

export const NewTicketWidget: React.FC<NewTicketWidgetProps> = ({ onCancel, onSuccess }) => {
  const { createTicket, isSubmitting, error } = useCreateTicket();

  // États locaux isolés dans le widget
  const [category, setCategory] = useState<'Incident Critique' | 'Évolution' | 'Administratif'>('Incident Critique');
  const [ci, setCi] = useState('general');
  const [subject, setSubject] = useState('');
  const [affectedAsset, setAffectedAsset] = useState('');
  const [incidentTime, setIncidentTime] = useState('');
  const [description, setDescription] = useState('');
  const [buttonVariant, setButtonVariant]=useState('primary');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // Le hook gère la logique de création
    const newTicketId = await createTicket({
      category, ci, subject, affectedAsset, incidentTime, description
    });

    // On délègue la navigation (ou l'action post-création) au composant parent
    if (newTicketId) {
      onSuccess(newTicketId);
    }
  };

  return (
    <Card>
      <CardHeader>
        <h1 className="text-xl font-bold text-slate-900 tracking-tight">Ouvrir un nouveau ticket</h1>
        <p className="text-sm text-slate-500 mt-0.5">Qualification de votre requête ITSM</p>
      </CardHeader>

      <CardContent className="p-6 sm:p-8">
        <form onSubmit={handleSubmit} className="space-y-8">

          {error && (
            <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md text-sm font-medium">
              {error}
            </div>
          )}

          {/* SECTION 1 : QUALIFICATION */}
          <div>
            <h2 className="text-base font-semibold text-slate-900 mb-4 border-b border-slate-100 pb-2">
              1. Qualification de la demande
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <Select
                label="Type de demande"
                value={category}
                onChange={(e) => {setCategory(e.target.value as any); setButtonVariant(e.target.value==="Incident Critique"?"danger":"primary")}}
                options={[
                  { value: 'Incident Critique', label: 'Incident Critique (Panne, Dégradation)' },
                  { value: 'Évolution', label: 'Évolution (Ajout de ressources, Modification)' },
                  { value: 'Administratif', label: 'Administratif (Facturation, Contrat)' },
                ]}
              />

              <Select
                label="Infrastructure concernée (CI)"
                value={ci}
                onChange={(e) => setCi(e.target.value)}
                options={[
                  { value: 'general', label: 'Général / Non spécifique' },
                  { value: 'px1', label: 'Serveur Proxmox Principal (Hyperviseur)' },
                  { value: 'fw1', label: 'Pare-feu Périphérique (WAN)' },
                  { value: 'db1', label: 'Base de données MariaDB' },
                ]}
              />
            </div>
          </div>

          {/* SECTION 2 : DÉTAILS */}
          <div>
            <h2 className="text-base font-semibold text-slate-900 mb-4 border-b border-slate-100 pb-2">
              2. Détails techniques
            </h2>
            <div className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <Input
                  label="Sujet de l'intervention"
                  required
                  value={subject}
                  onChange={(e) => setSubject(e.target.value)}
                  placeholder="Ex: Perte de paquets sur le lien WAN principal"
                />

                <Input
                  label="Équipement ou Produit concerné (Optionnel)"
                  value={affectedAsset}
                  onChange={(e) => setAffectedAsset(e.target.value)}
                  placeholder="Ex: Ordinateur Direction, Imprimante X, etc."
                />
              </div>

              {category === 'Incident Critique' && (
                <div className="animate-in fade-in slide-in-from-top-2 duration-300 max-w-sm">
                  <Input
                    type="datetime-local"
                    label="Heure exacte du début de l'incident"
                    required
                    value={incidentTime}
                    onChange={(e) => setIncidentTime(e.target.value)}
                    className="bg-red-50/30 border-red-300 focus:border-red-500 focus:ring-red-500"
                  />
                </div>
              )}

              <Textarea
                label="Description détaillée"
                required
                rows={6}
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="Décrivez précisément votre besoin ou les symptômes observés..."
              />
            </div>
          </div>

          {/* ACTIONS */}
          <div className="pt-6 flex justify-end gap-3 border-t border-slate-100">
            <Button
              type="button"
              variant="outline"
              onClick={onCancel} // Utilisation de la prop
            >
              Annuler
            </Button>
            <Button
              type="submit"
              isLoading={isSubmitting}
              variant={buttonVariant}
            >
              Soumettre le ticket
            </Button>
          </div>

        </form>
      </CardContent>
    </Card>
  );
};

export default NewTicketWidget;