'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { format } from 'date-fns';
import { Calendar as CalendarIcon, Clock, Send } from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
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 { useSubmitCorrection } from '@/hooks/hr/use-time-tracking';
import { useToast } from '@/hooks/use-toast';
import type { TimeEntry, TimeEntryCorrectionDto } from '@/types/hr';

interface TimeEntryFormProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  entry?: TimeEntry | null;
}

/**
 * Form for requesting time entry corrections
 */
export function TimeEntryForm({ open, onOpenChange, entry }: TimeEntryFormProps) {
  const t = useTranslations('hr.timeTracking');
  const tCommon = useTranslations('common');
  const { toast } = useToast();

  const submitCorrection = useSubmitCorrection();

  // Form state
  const [formData, setFormData] = useState<Partial<TimeEntryCorrectionDto>>({
    date: entry?.date || format(new Date(), 'yyyy-MM-dd'),
    clockIn: entry?.clockIn || '',
    clockOut: entry?.clockOut || '',
    breakStart: entry?.breakStart || '',
    breakEnd: entry?.breakEnd || '',
    note: '',
  });

  // Update form when entry changes
  const resetForm = () => {
    setFormData({
      date: entry?.date || format(new Date(), 'yyyy-MM-dd'),
      clockIn: entry?.clockIn || '',
      clockOut: entry?.clockOut || '',
      breakStart: entry?.breakStart || '',
      breakEnd: entry?.breakEnd || '',
      note: '',
    });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!formData.note?.trim()) {
      toast({
        title: tCommon('error'),
        description: t('noteRequired'),
        variant: 'destructive',
      });
      return;
    }

    try {
      await submitCorrection.mutateAsync({
        date: formData.date!,
        clockIn: formData.clockIn,
        clockOut: formData.clockOut,
        breakStart: formData.breakStart,
        breakEnd: formData.breakEnd,
        note: formData.note,
      });

      toast({
        title: t('correctionSubmitted'),
        description: t('correctionSubmittedDesc'),
      });

      onOpenChange(false);
      resetForm();
    } catch {
      toast({
        title: tCommon('error'),
        description: t('errorSubmitCorrection'),
        variant: 'destructive',
      });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Clock className="h-5 w-5" />
            {t('requestCorrection')}
          </DialogTitle>
          <DialogDescription>{t('requestCorrectionDesc')}</DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Date */}
          <div className="space-y-2">
            <Label htmlFor="date">{t('date')}</Label>
            <div className="relative">
              <CalendarIcon className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                id="date"
                type="date"
                value={formData.date}
                onChange={(e) => setFormData((prev) => ({ ...prev, date: e.target.value }))}
                className="pl-10"
              />
            </div>
          </div>

          {/* Clock In / Clock Out */}
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="clockIn">{t('clockIn')}</Label>
              <Input
                id="clockIn"
                type="time"
                value={formData.clockIn}
                onChange={(e) =>
                  setFormData((prev) => ({ ...prev, clockIn: e.target.value }))
                }
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="clockOut">{t('clockOut')}</Label>
              <Input
                id="clockOut"
                type="time"
                value={formData.clockOut}
                onChange={(e) =>
                  setFormData((prev) => ({ ...prev, clockOut: e.target.value }))
                }
              />
            </div>
          </div>

          {/* Break Start / Break End */}
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="breakStart">{t('breakStart')}</Label>
              <Input
                id="breakStart"
                type="time"
                value={formData.breakStart}
                onChange={(e) =>
                  setFormData((prev) => ({ ...prev, breakStart: e.target.value }))
                }
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="breakEnd">{t('breakEnd')}</Label>
              <Input
                id="breakEnd"
                type="time"
                value={formData.breakEnd}
                onChange={(e) =>
                  setFormData((prev) => ({ ...prev, breakEnd: e.target.value }))
                }
              />
            </div>
          </div>

          {/* Note (required for corrections) */}
          <div className="space-y-2">
            <Label htmlFor="note">
              {t('reason')} <span className="text-destructive">*</span>
            </Label>
            <Textarea
              id="note"
              placeholder={t('reasonPlaceholder')}
              value={formData.note}
              onChange={(e) => setFormData((prev) => ({ ...prev, note: e.target.value }))}
              rows={3}
            />
          </div>

          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={submitCorrection.isPending}
            >
              {tCommon('cancel')}
            </Button>
            <Button type="submit" disabled={submitCorrection.isPending} className="gap-2">
              <Send className="h-4 w-4" />
              {tCommon('submit')}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
