import React, { useState, useEffect } from 'react';
import { Plus, Pencil, Trash2, Loader2, Eye } from 'lucide-react';
import { useForm, Controller } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { {{ model.name }} } from '../../services/{{ model.module_name }}';
import { use{{ model.name }}Store } from '../../stores/use{{ model.name }}Store';
import { Button } from '../../components/ui/button';
import { Input } from '../../components/ui/input';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../components/ui/table';
import { Modal } from '../../components/ui/modal';
import { Label } from '../../components/ui/label';
import { Badge } from '../../components/ui/badge';
import { Switch } from '../../components/ui/switch';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../components/ui/select';
import { ImageUpload } from '../../components/ui/image-upload';
import { FileUpload } from '../../components/ui/file-upload';
import { SearchableSelect } from '../../components/ui/searchable-select';
{% for fk in model.foreign_keys %}
import { get{{ fk.target_endpoint.capitalize() }} } from '../../services/{{ fk.target_service }}';
{% endfor %}
{% if model.m2m_fields %}
{% for m2m in model.m2m_fields %}
import { get{{ m2m.target_endpoint.capitalize() }} } from '../../services/{{ m2m.target_service }}';
{% endfor %}
{% endif %}

const {{ model.name }}Page: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { data, loading, fetchData, createItem, updateItem, deleteItem } = use{{ model.name }}Store();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);

  const { register, handleSubmit, reset, setValue, control } = useForm();

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const handleCreate = () => {
    setEditingId(null);
    reset();
    setIsModalOpen(true);
  };

  const handleEdit = (record: {{ model.name }}) => {
    setEditingId(record.id);
    // Set form values
    {% for field in model.fields %}
    {% if ('c' in field.permissions or 'u' in field.permissions) and 'r' in field.permissions %}
    setValue('{{ field.name }}', record.{{ field.name }});
    {% endif %}
    {% endfor %}
    setIsModalOpen(true);
  };

  const handleDelete = async (id: number) => {
    if (!confirm(t('common.confirm_delete'))) return;
    try {
      await deleteItem(id);
    } catch (error) {
      console.error(error);
    }
  };

  const onSubmit = async (values: any) => {
    try {
      if (editingId) {
        await updateItem(editingId, values);
      } else {
        await createItem(values);
      }
      setIsModalOpen(false);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold tracking-tight">{t('models.{{ model.module_name }}.name')}s</h1>
        <Button onClick={handleCreate}>
          <Plus className="mr-2 h-4 w-4" /> {t('common.create')} {t('models.{{ model.module_name }}.name')}
        </Button>
      </div>

      <div className="border rounded-md">
        <Table>
          <TableHeader>
            <TableRow>
              {% for field in model.fields %}
              {% if 'r' in field.permissions %}
              <TableHead>{t('{{ field.label_key }}')}</TableHead>
              {% endif %}
              {% endfor %}
              <TableHead className="w-[100px]">{t('common.actions')}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
                <TableRow>
                    <TableCell colSpan={ {{ model.fields|length + 1 }} } className="h-24 text-center">
                        <Loader2 className="h-6 w-6 animate-spin mx-auto" />
                    </TableCell>
                </TableRow>
            ) : data.length === 0 ? (
                <TableRow>
                    <TableCell colSpan={ {{ model.fields|length + 1 }} } className="h-24 text-center">
                        {t('common.no result')}
                    </TableCell>
                </TableRow>
            ) : (
                data.map((item) => (
                <TableRow key={item.id}>
                    {% for field in model.fields %}
                    {% if 'r' in field.permissions %}
                    <TableCell>
                        {% if field.ui_type == 'bool' %}
                        <Badge variant={item.{{ field.name }} ? "default" : "secondary"}>
                            {item.{{ field.name }} ? 'Yes' : 'No'}
                        </Badge>
                        {% elif field.ui_type == 'image' %}
                        <div className="h-10 w-10 overflow-hidden rounded-md border bg-muted">
                            <img
                                src={item.{{ field.name }} || 'https://placehold.co/100?text=No+Image'}
                                alt="{{ field.name }}"
                                className="h-full w-full object-cover"
                                onError={(e) => {
                                    (e.target as HTMLImageElement).src = 'https://placehold.co/100?text=Error';
                                }}
                            />
                        </div>
                        {% elif field.ui_type == 'file' %}
                        {item.{{ field.name }} ? (
                            <div className="flex items-center gap-2">
                                <span
                                    className="flex items-center text-primary cursor-pointer hover:underline"
                                    title={item.{{ field.name }}}
                                    onClick={() => {
                                        // TODO: Open preview
                                    }}
                                >
                                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="mr-1"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>
                                    File
                                </span>
                                {% if field.allow_download %}
                                <a
                                    href={item.{{ field.name }}}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="text-muted-foreground hover:text-primary"
                                    title="Download"
                                >
                                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/></svg>
                                </a>
                                {% endif %}
                            </div>
                        ) : (
                            <span className="text-muted-foreground">-</span>
                        )}
                        {% elif field.is_enum %}
                        <Badge variant="outline">{item.{{ field.name }}}</Badge>
                        {% else %}
                        {String(item.{{ field.name }})}
                        {% endif %}
                    </TableCell>
                    {% endif %}
                    {% endfor %}
                    <TableCell className="flex items-center gap-2">
                        <Button variant="ghost" size="icon" onClick={() => navigate(`/{{ model.module_name }}s/${item.id}`)}>
                            <Eye className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="icon" onClick={() => handleEdit(item)}>
                            <Pencil className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="icon" className="text-destructive" onClick={() => handleDelete(item.id)}>
                            <Trash2 className="h-4 w-4" />
                        </Button>
                    </TableCell>
                </TableRow>
                ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* Pagination Controls */}
      <div className="flex items-center justify-end space-x-2">
        <div className="flex-1 text-sm text-muted-foreground">
            Page {use{{ model.name }}Store(state => state.page)} of {Math.ceil(use{{ model.name }}Store(state => state.total) / use{{ model.name }}Store(state => state.size)) || 1}
        </div>
        <div className="space-x-2">
            <Button
                variant="outline"
                size="sm"
                onClick={() => fetchData(use{{ model.name }}Store.getState().page - 1, use{{ model.name }}Store.getState().size)}
                disabled={use{{ model.name }}Store(state => state.page) <= 1 || loading}
            >
                {t('common.previous')}
            </Button>
            <Button
                variant="outline"
                size="sm"
                onClick={() => fetchData(use{{ model.name }}Store.getState().page + 1, use{{ model.name }}Store.getState().size)}
                disabled={use{{ model.name }}Store(state => state.page) >= Math.ceil(use{{ model.name }}Store(state => state.total) / use{{ model.name }}Store(state => state.size)) || loading}
            >
                {t('common.next')}
            </Button>
        </div>
      </div>

      <Modal
        title={editingId ? `${t('common.edit')} {{ model.name }}` : `${t('common.create')} {{ model.name }}`}
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
      >
            <div className="max-h-[80vh] overflow-y-auto pr-2">
                <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
          {% for field in model.fields %}
          {% if 'c' in field.permissions or 'u' in field.permissions %}
          <div className="space-y-2">
            <Label htmlFor="{{ field.name }}">{t('{{ field.label_key }}')}</Label>
            {% if field.ui_type == 'bool' %}
            <div className="flex items-center space-x-2">
                <Controller
                    control={control}
                    name="{{ field.name }}"
                    defaultValue={ {{ 'true' if field.default else 'false' }} }
                    render={({ field: { onChange, value } }) => (
                        <Switch checked={value} onCheckedChange={onChange} id="{{ field.name }}" />
                    )}
                />
                <Label htmlFor="{{ field.name }}" className="font-normal text-muted-foreground">
                    {t('{{ field.label_key }}')}
                </Label>
            </div>
            {% elif field.ui_type == 'image' %}
            <Controller
                control={control}
                name="{{ field.name }}"
                render={({ field: { onChange, value } }) => (
                    <ImageUpload
                        value={value}
                        onChange={onChange}
                    />
                )}
            />
            {% elif field.ui_type == 'file' %}
                        <Controller
                            control={control}
                            name="{{ field.name }}"
                            render={({ field: { onChange, value } }) => (
                                <FileUpload
                                    value={value}
                                    onChange={onChange}
                                    allowDownload={ {{ "true" if field.allow_download else "false" }} }
                                />
                            )}
                        />
                        {% elif field.is_enum %}
            <Controller
                control={control}
                name="{{ field.name }}"
                render={({ field: { onChange, value } }) => (
                    <Select onValueChange={onChange} defaultValue={value}>
                        <SelectTrigger>
                            <SelectValue placeholder={`${t('common.select')} ${t('{{ field.label_key }}')}`} />
                        </SelectTrigger>
                        <SelectContent>
                            {% for enum_val in field.enum_values %}
                            <SelectItem value="{{ enum_val }}">{{ enum_val }}</SelectItem>
                            {% endfor %}
                        </SelectContent>
                    </Select>
                )}
            />
            {% elif field.fk_info %}
            <Controller
                control={control}
                name="{{ field.name }}"
                render={({ field: { onChange, value } }) => (
                    <SearchableSelect
                        value={value}
                        onValueChange={onChange}
                        placeholder={`${t('common.select')} ${t('{{ field.label_key }}')}`}
                        searchPlaceholder={`${t('common.search')} ${t('models.{{ field.fk_info.target_service }}.name')}...`}
                        loadOptions={async (query) => {
                            const response = await get{{ field.fk_info.target_endpoint.capitalize() }}(1, 20, query);
                            return response.items.map((item: any) => ({
                                label: item.{{ field.fk_info.label_field }} || item.id,
                                value: item.id
                            }));
                        }}
                    />
                )}
            />
            {% else %}
            <Input
                id="{{ field.name }}"
                {% if field.ui_type == 'int' or field.ui_type == 'float' %}
                type="number"
                {% else %}
                type="text"
                {% endif %}
                {...register('{{ field.name }}', { required: !editingId ? {{ 'true' if field.required and not field.create_optional else 'false' }} : {{ 'true' if field.required and not field.update_optional else 'false' }} })}
            />
            {% endif %}
          </div>
          {% endif %}
          {% endfor %}

          {% if model.m2m_fields %}
          {% for m2m in model.m2m_fields %}
          <div className="space-y-2">
            <Label>{t('models.{{ m2m.target_service }}.name')}s</Label>
            <Controller
                control={control}
                name="{{ m2m.name }}"
                render={({ field: { onChange, value } }) => (
                    <SearchableSelect
                        value={value}
                        onValueChange={onChange}
                        multiple={true}
                        placeholder={`${t('common.select')} ${t('models.{{ m2m.target_service }}.name')}s`}
                        searchPlaceholder={`${t('common.search')} ${t('models.{{ m2m.target_service }}.name')}...`}
                        loadOptions={async (query) => {
                            const response = await get{{ m2m.target_endpoint.capitalize() }}(1, 20, query);
                            return response.items.map((item: any) => ({
                                label: item.{{ m2m.label_field }} || item.id,
                                value: item.id
                            }));
                        }}
                    />
                )}
            />
          </div>
          {% endfor %}
          {% endif %}
          <div className="flex justify-end space-x-2 pt-4">
            <Button variant="outline" type="button" onClick={() => setIsModalOpen(false)}>{t('common.cancel')}</Button>
            <Button type="submit">{t('common.save')}</Button>
          </div>
        </form>
            </div>
      </Modal>
    </div>
  );
};

export default {{ model.name }}Page;
