import React, { useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useCompany, useCreateCompany, useUpdateCompany } from '@/api/hooks';
import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { Skeleton } from '@/components/ui/Skeleton';
import { useToast } from '@/components/ui/Toast';
import { UnsavedChangesGuard } from '@/components/shared/UnsavedChangesGuard';

const companySchema = z.object({
  name: z.string().min(1, 'Name ist erforderlich').max(100, 'Maximal 100 Zeichen'),
  account_number: z.string().max(40, 'Maximal 40 Zeichen').optional().or(z.literal('')),
  industry: z.string().max(50, 'Maximal 50 Zeichen').optional().or(z.literal('')),
  phone: z.string().max(30, 'Maximal 30 Zeichen').optional().or(z.literal('')),
  email: z.string().email('Ungültige E-Mail-Adresse').max(255).optional().or(z.literal('')),
  website: z.string().max(500, 'Maximal 500 Zeichen').optional().or(z.literal('')),
  description: z.string().optional().or(z.literal('')),
});

type CompanyFormValues = z.infer<typeof companySchema>;

export function CompanyFormPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const toast = useToast();
  const isEdit = !!id;

  const { data: company, isLoading } = useCompany(isEdit ? id : undefined);
  const createMutation = useCreateCompany();
  const updateMutation = useUpdateCompany();

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors, isDirty, isSubmitting },
  } = useForm<CompanyFormValues>({
    resolver: zodResolver(companySchema),
    defaultValues: {
      name: '',
      account_number: '',
      industry: '',
      phone: '',
      email: '',
      website: '',
      description: '',
    },
  });

  useEffect(() => {
    if (isEdit && company) {
      reset({
        name: company.name || '',
        account_number: company.account_number || '',
        industry: company.industry || '',
        phone: company.phone || '',
        email: company.email || '',
        website: company.website || '',
        description: company.description || '',
      });
    }
  }, [company, isEdit, reset]);

  const onSubmit = async (values: CompanyFormValues) => {
    try {
      if (isEdit && id) {
        await updateMutation.mutateAsync({ id, data: values });
        toast.success(t('companies.updated'));
        navigate(`/companies/${id}`);
      } else {
        const result = await createMutation.mutateAsync(values) as { id: string };
        toast.success(t('companies.created'));
        navigate(`/companies/${result.id}`);
      }
    } catch (err: any) {
      toast.error(err.message || (isEdit ? t('companies.updateFailed') : t('companies.createFailed')));
    }
  };

  if (isEdit && isLoading) {
    return (
      <div className="p-6 max-w-4xl mx-auto" data-testid="company-form-page">
        <Skeleton className="h-8 w-48 mb-6" />
        <Skeleton className="h-96" />
      </div>
    );
  }

  return (
    <div className="p-6 max-w-4xl mx-auto" data-testid="company-form-page">
      <UnsavedChangesGuard isDirty={isDirty} />
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-4">
          <Button variant="ghost" onClick={() => navigate(-1)}>
            ← {t('common.back')}
          </Button>
          <h1 className="text-2xl font-bold text-secondary-900">
            {isEdit ? t('companies.edit') : t('companies.create')}
          </h1>
        </div>
      </div>

      <form onSubmit={handleSubmit(onSubmit)} noValidate className="space-y-4">
        <Card title={t('companies.name')}>
          <Input
            {...register('name')}
            label={t('companies.name')}
            required
            error={errors.name?.message}
            placeholder="TechCorp GmbH"
            data-testid="company-name-input"
          />
        </Card>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <Card title={t('companies.accountNumber')}>
            <Input
              {...register('account_number')}
              label={t('companies.accountNumber')}
              error={errors.account_number?.message}
              placeholder="K-00123"
            />
          </Card>
          <Card title={t('companies.industry')}>
            <Input
              {...register('industry')}
              label={t('companies.industry')}
              error={errors.industry?.message}
              placeholder="IT & Software"
            />
          </Card>
          <Card title={t('companies.phone')}>
            <Input
              {...register('phone')}
              label={t('companies.phone')}
              error={errors.phone?.message}
              placeholder="+49 30 1234567"
            />
          </Card>
          <Card title={t('companies.email')}>
            <Input
              {...register('email')}
              label={t('companies.email')}
              type="email"
              error={errors.email?.message}
              placeholder="info@techcorp.de"
            />
          </Card>
        </div>

        <Card title={t('companies.website')}>
          <Input
            {...register('website')}
            label={t('companies.website')}
            error={errors.website?.message}
            placeholder="https://www.techcorp.de"
          />
        </Card>

        <Card title={t('companies.description')}>
          <textarea
            {...register('description')}
            className="w-full px-3 py-2 text-sm rounded-md border border-secondary-300 focus:outline-none focus:ring-2 focus:ring-primary-500 min-h-24"
            placeholder="Firmenbeschreibung..."
            aria-label={t('companies.description')}
          />
          {errors.description && (
            <p className="mt-1 text-sm text-danger-600">{errors.description.message}</p>
          )}
        </Card>

        <div className="flex justify-end gap-3">
          <Button variant="secondary" onClick={() => navigate(-1)}>
            {t('common.cancel')}
          </Button>
          <Button type="submit" isLoading={isSubmitting} data-testid="company-submit-btn">
            {isEdit ? t('common.save') : t('common.create')}
          </Button>
        </div>
      </form>
    </div>
  );
}
