'use client';

import { useState } from 'react';
import { useTranslations, useLocale } from 'next-intl';
import { Camera, Loader2 } from 'lucide-react';

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';
import type { S3Status, S3StatusType } from '@/hooks/lean/use-s3-plans';

interface S3StatusModalProps {
  /** Whether the modal is open */
  open: boolean;
  /** Callback when modal should close */
  onOpenChange: (open: boolean) => void;
  /** Current status entry */
  status: S3Status | null;
  /** Category name for display */
  categoryName: string;
  /** Callback when status is updated */
  onUpdate: (statusId: string, data: { status: S3StatusType; note?: string }) => void;
  /** Whether update is in progress */
  isUpdating?: boolean;
}

/**
 * Status options for selection
 */
const STATUS_OPTIONS: Array<{
  value: S3StatusType;
  labelKey: string;
  descriptionKey: string;
  bg: string;
  selectedBg: string;
  ring: string;
}> = [
  {
    value: 'NOT_APPLICABLE',
    labelKey: 'status.not_started',
    descriptionKey: 'statusDescNotStarted',
    bg: 'bg-gray-200 dark:bg-gray-700',
    selectedBg: 'bg-gray-300 dark:bg-gray-600',
    ring: 'ring-gray-400',
  },
  {
    value: 'YELLOW',
    labelKey: 'status.in_progress',
    descriptionKey: 'statusDescInProgress',
    bg: 'bg-yellow-100 dark:bg-yellow-900/30',
    selectedBg: 'bg-yellow-200 dark:bg-yellow-800/50',
    ring: 'ring-yellow-500',
  },
  {
    value: 'GREEN',
    labelKey: 'status.completed',
    descriptionKey: 'statusDescCompleted',
    bg: 'bg-green-100 dark:bg-green-900/30',
    selectedBg: 'bg-green-200 dark:bg-green-800/50',
    ring: 'ring-green-500',
  },
  {
    value: 'RED',
    labelKey: 'status.issue',
    descriptionKey: 'statusDescIssue',
    bg: 'bg-red-100 dark:bg-red-900/30',
    selectedBg: 'bg-red-200 dark:bg-red-800/50',
    ring: 'ring-red-500',
  },
];

/**
 * S3 Status Modal Component
 * Modal dialog for editing status details including status, notes, and photos
 */
export function S3StatusModal({
  open,
  onOpenChange,
  status,
  categoryName,
  onUpdate,
  isUpdating = false,
}: S3StatusModalProps) {
  const t = useTranslations('common');
  const tLean = useTranslations('lean');
  const tS3 = useTranslations('lean.s3');
  const locale = useLocale();

  const [selectedStatus, setSelectedStatus] = useState<S3StatusType>(
    status?.status ?? 'NOT_APPLICABLE'
  );
  const [note, setNote] = useState(status?.note ?? '');

  // Reset form when status changes
  const handleOpenChange = (newOpen: boolean) => {
    if (newOpen && status) {
      setSelectedStatus(status.status);
      setNote(status.note ?? '');
    }
    onOpenChange(newOpen);
  };

  const handleSubmit = () => {
    if (!status) return;

    onUpdate(status.id, {
      status: selectedStatus,
      note: note.trim() || undefined,
    });
  };

  if (!status) return null;

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>{tS3('editStatus')}</DialogTitle>
          <DialogDescription>
            {categoryName} - KW {status.week}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {/* Status Selection */}
          <div className="space-y-3">
            <Label>{tLean('status')}</Label>
            <div className="grid grid-cols-2 gap-2">
              {STATUS_OPTIONS.map((option) => (
                <button
                  key={option.value}
                  type="button"
                  onClick={() => setSelectedStatus(option.value)}
                  className={cn(
                    'p-3 rounded-lg border-2 text-left transition-all',
                    selectedStatus === option.value
                      ? `${option.selectedBg} border-transparent ring-2 ${option.ring}`
                      : `${option.bg} border-transparent hover:border-muted-foreground/20`
                  )}
                >
                  <div className="font-medium text-sm">{tS3(option.labelKey as never)}</div>
                  <div className="text-xs text-muted-foreground">
                    {tS3(option.descriptionKey as never)}
                  </div>
                </button>
              ))}
            </div>
          </div>

          {/* Note Input */}
          <div className="space-y-2">
            <Label htmlFor="note">{tS3('noteOptional')}</Label>
            <Textarea
              id="note"
              placeholder={tS3('additionalInfo')}
              value={note}
              onChange={(e) => setNote(e.target.value)}
              rows={3}
              maxLength={1000}
            />
            <div className="text-xs text-muted-foreground text-right">
              {note.length}/1000 {tS3('characters')}
            </div>
          </div>

          {/* Photo (placeholder for future implementation) */}
          {status.photo && (
            <div className="space-y-2">
              <Label>{tS3('photo')}</Label>
              <div className="relative aspect-video rounded-lg overflow-hidden bg-muted">
                <img
                  src={status.photo}
                  alt={tS3('statusPhoto')}
                  className="object-cover w-full h-full"
                />
              </div>
            </div>
          )}

          {/* Upload Button (placeholder) */}
          <Button variant="outline" className="w-full" disabled>
            <Camera className="h-4 w-4 mr-2" />
            {tS3('addPhoto')}
          </Button>

          {/* Completion Info */}
          {status.completedBy && status.completedAt && (
            <div className="text-xs text-muted-foreground border-t pt-4">
              {tS3('completedByAt', {
                name: `${status.completedBy.firstName} ${status.completedBy.lastName}`,
                date: new Date(status.completedAt).toLocaleString(locale === 'de' ? 'de-DE' : 'en-US'),
              })}
            </div>
          )}
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isUpdating}
          >
            {t('cancel')}
          </Button>
          <Button onClick={handleSubmit} disabled={isUpdating}>
            {isUpdating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
            {t('save')}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
